1 /* $NetBSD: refclock_chu.c,v 1.1.1.2 2012/01/31 21:25:55 kardel Exp $ */ 2 3 /* 4 * refclock_chu - clock driver for Canadian CHU time/frequency station 5 */ 6 #ifdef HAVE_CONFIG_H 7 #include <config.h> 8 #endif 9 10 #if defined(REFCLOCK) && defined(CLOCK_CHU) 11 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 18 #include <stdio.h> 19 #include <ctype.h> 20 #include <math.h> 21 22 #ifdef HAVE_AUDIO 23 #include "audio.h" 24 #endif /* HAVE_AUDIO */ 25 26 #define ICOM 1 /* undefine to suppress ICOM code */ 27 28 #ifdef ICOM 29 #include "icom.h" 30 #endif /* ICOM */ 31 /* 32 * Audio CHU demodulator/decoder 33 * 34 * This driver synchronizes the computer time using data encoded in 35 * radio transmissions from Canadian time/frequency station CHU in 36 * Ottawa, Ontario. Transmissions are made continuously on 3330 kHz, 37 * 7850 kHz and 14670 kHz in upper sideband, compatible AM mode. An 38 * ordinary shortwave receiver can be tuned manually to one of these 39 * frequencies or, in the case of ICOM receivers, the receiver can be 40 * tuned automatically as propagation conditions change throughout the 41 * day and season. 42 * 43 * The driver requires an audio codec or sound card with sampling rate 8 44 * kHz and mu-law companding. This is the same standard as used by the 45 * telephone industry and is supported by most hardware and operating 46 * systems, including Solaris, SunOS, FreeBSD, NetBSD and Linux. In this 47 * implementation, only one audio driver and codec can be supported on a 48 * single machine. 49 * 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 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. 59 * 60 * The CHU time broadcast includes an audio signal compatible with the 61 * Bell 103 modem standard (mark = 2225 Hz, space = 2025 Hz). The signal 62 * consists of nine, ten-character bursts transmitted at 300 bps between 63 * seconds 31 and 39 of each minute. Each character consists of eight 64 * data bits plus one start bit and two stop bits to encode two hex 65 * digits. The burst data consist of five characters (ten hex digits) 66 * followed by a repeat of these characters. In format A, the characters 67 * are repeated in the same polarity; in format B, the characters are 68 * repeated in the opposite polarity. 69 * 70 * Format A bursts are sent at seconds 32 through 39 of the minute in 71 * hex digits (nibble swapped) 72 * 73 * 6dddhhmmss6dddhhmmss 74 * 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. 81 * 82 * Format B bursts are sent at second 31 of the minute in hex digits 83 * 84 * xdyyyyttaaxdyyyyttaa 85 * 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. 90 * 91 * The x is coded 92 * 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. 97 * 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 - 9 * 11/300 = 0.170 second. Depending on the 102 * UART, character interrupts can vary somewhere between the end of bit 103 * 9 and end of bit 11. These eccentricities can be corrected along with 104 * the radio propagation delay using fudge time 1. 105 * 106 * Debugging aids 107 * 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.Each line begins with the format code 113 * chuA or chuB followed by the status code and signal level (0-9999). 114 * The remainder of the line is as follows. 115 * 116 * Following is format A: 117 * 118 * n b f s m code 119 * 120 * where n is the number of characters in the burst (0-10), b the burst 121 * distance (0-40), f the field alignment (-1, 0, 1), s the 122 * synchronization distance (0-16), m the burst number (2-9) and code 123 * the burst characters as received. Note that the hex digits in each 124 * character are reversed, so the burst 125 * 126 * 10 38 0 16 9 06851292930685129293 127 * 128 * is interpreted as containing 10 characters with burst distance 38, 129 * field alignment 0, synchronization distance 16 and burst number 9. 130 * The nibble-swapped timecode shows day 58, hour 21, minute 29 and 131 * second 39. 132 * 133 * Following is format B: 134 * 135 * n b s code 136 * 137 * where n is the number of characters in the burst (0-10), b the burst 138 * distance (0-40), s the synchronization distance (0-40) and code the 139 * burst characters as received. Note that the hex digits in each 140 * character are reversed and the last ten digits inverted, so the burst 141 * 142 * 10 40 1091891300ef6e76ec 143 * 144 * is interpreted as containing 10 characters with burst distance 40. 145 * The nibble-swapped timecode shows DUT1 +0.1 second, year 1998 and TAI 146 * - UTC 31 seconds. 147 * 148 * Each line is preceeded by the code chuA or chuB, as appropriate. If 149 * the audio driver is compiled, the current gain (0-255) and relative 150 * signal level (0-9999) follow the code. The receiver volume control 151 * should be set so that the gain is somewhere near the middle of the 152 * range 0-255, which results in a signal level near 1000. 153 * 154 * In addition to the above, the reference timecode is updated and 155 * written to the clockstats file and debug score after the last burst 156 * received in the minute. The format is 157 * 158 * sq yyyy ddd hh:mm:ss l s dd t agc ident m b 159 * 160 * s '?' before first synchronized and ' ' after that 161 * q status code (see below) 162 * yyyy year 163 * ddd day of year 164 * hh:mm:ss time of day 165 * l leap second indicator (space, L or D) 166 * dst Canadian daylight code (opaque) 167 * t number of minutes since last synchronized 168 * agc audio gain (0 - 255) 169 * ident identifier (CHU0 3330 kHz, CHU1 7850 kHz, CHU2 14670 kHz) 170 * m signal metric (0 - 100) 171 * b number of timecodes for the previous minute (0 - 59) 172 * 173 * Fudge factors 174 * 175 * For accuracies better than the low millisceconds, fudge time1 can be 176 * set to the radio propagation delay from CHU to the receiver. This can 177 * be done conviently using the minimuf program. 178 * 179 * Fudge flag4 causes the dubugging output described above to be 180 * recorded in the clockstats file. When the audio driver is compiled, 181 * fudge flag2 selects the audio input port, where 0 is the mike port 182 * (default) and 1 is the line-in port. It does not seem useful to 183 * select the compact disc player port. Fudge flag3 enables audio 184 * monitoring of the input signal. For this purpose, the monitor gain is 185 * set to a default value. 186 * 187 * The audio codec code is normally compiled in the driver if the 188 * architecture supports it (HAVE_AUDIO defined), but is used only if 189 * the link /dev/chu_audio is defined and valid. The serial port code is 190 * always compiled in the driver, but is used only if the autdio codec 191 * is not available and the link /dev/chu%d is defined and valid. 192 * 193 * The ICOM code is normally compiled in the driver if selected (ICOM 194 * defined), but is used only if the link /dev/icom%d is defined and 195 * valid and the mode keyword on the server configuration command 196 * specifies a nonzero mode (ICOM ID select code). The C-IV speed is 197 * 9600 bps if the high order 0x80 bit of the mode is zero and 1200 bps 198 * if one. The C-IV trace is turned on if the debug level is greater 199 * than one. 200 * 201 * Alarm codes 202 * 203 * CEVNT_BADTIME invalid date or time 204 * CEVNT_PROP propagation failure - no stations heard 205 */ 206 /* 207 * Interface definitions 208 */ 209 #define SPEED232 B300 /* uart speed (300 baud) */ 210 #define PRECISION (-10) /* precision assumed (about 1 ms) */ 211 #define REFID "CHU" /* reference ID */ 212 #define DEVICE "/dev/chu%d" /* device name and unit */ 213 #define SPEED232 B300 /* UART speed (300 baud) */ 214 #ifdef ICOM 215 #define TUNE .001 /* offset for narrow filter (MHz) */ 216 #define DWELL 5 /* minutes in a dwell */ 217 #define NCHAN 3 /* number of channels */ 218 #define ISTAGE 3 /* number of integrator stages */ 219 #endif /* ICOM */ 220 221 #ifdef HAVE_AUDIO 222 /* 223 * Audio demodulator definitions 224 */ 225 #define SECOND 8000 /* nominal sample rate (Hz) */ 226 #define BAUD 300 /* modulation rate (bps) */ 227 #define OFFSET 128 /* companded sample offset */ 228 #define SIZE 256 /* decompanding table size */ 229 #define MAXAMP 6000. /* maximum signal level */ 230 #define MAXCLP 100 /* max clips above reference per s */ 231 #define SPAN 800. /* min envelope span */ 232 #define LIMIT 1000. /* soft limiter threshold */ 233 #define AGAIN 6. /* baseband gain */ 234 #define LAG 10 /* discriminator lag */ 235 #define DEVICE_AUDIO "/dev/audio" /* device name */ 236 #define DESCRIPTION "CHU Audio/Modem Receiver" /* WRU */ 237 #define AUDIO_BUFSIZ 240 /* audio buffer size (30 ms) */ 238 #else 239 #define DESCRIPTION "CHU Modem Receiver" /* WRU */ 240 #endif /* HAVE_AUDIO */ 241 242 /* 243 * Decoder definitions 244 */ 245 #define CHAR (11. / 300.) /* character time (s) */ 246 #define BURST 11 /* max characters per burst */ 247 #define MINCHAR 9 /* min characters per burst */ 248 #define MINDIST 28 /* min burst distance (of 40) */ 249 #define MINSYNC 8 /* min sync distance (of 16) */ 250 #define MINSTAMP 20 /* min timestamps (of 60) */ 251 #define MINMETRIC 50 /* min channel metric (of 160) */ 252 253 /* 254 * The on-time synchronization point for the driver is the last stop bit 255 * of the first character 170 ms. The modem delay is 0.8 ms, while the 256 * receiver delay is approxmately 4.7 ms at 2125 Hz. The fudge value 1.3 257 * ms due to the codec and other causes was determined by calibrating to 258 * a PPS signal from a GPS receiver. The additional propagation delay 259 * specific to each receiver location can be programmed in the fudge 260 * time1. 261 * 262 * The resulting offsets with a 2.4-GHz P4 running FreeBSD 6.1 are 263 * generally within 0.5 ms short term with 0.3 ms jitter. The long-term 264 * offsets vary up to 0.3 ms due to ionospheric layer height variations. 265 * The processor load due to the driver is 0.4 percent. 266 */ 267 #define PDELAY ((170 + .8 + 4.7 + 1.3) / 1000) /* system delay (s) */ 268 269 /* 270 * Status bits (status) 271 */ 272 #define RUNT 0x0001 /* runt burst */ 273 #define NOISE 0x0002 /* noise burst */ 274 #define BFRAME 0x0004 /* invalid format B frame sync */ 275 #define BFORMAT 0x0008 /* invalid format B data */ 276 #define AFRAME 0x0010 /* invalid format A frame sync */ 277 #define AFORMAT 0x0020 /* invalid format A data */ 278 #define DECODE 0x0040 /* invalid data decode */ 279 #define STAMP 0x0080 /* too few timestamps */ 280 #define AVALID 0x0100 /* valid A frame */ 281 #define BVALID 0x0200 /* valid B frame */ 282 #define INSYNC 0x0400 /* clock synchronized */ 283 #define METRIC 0x0800 /* one or more stations heard */ 284 285 /* 286 * Alarm status bits (alarm) 287 * 288 * These alarms are set at the end of a minute in which at least one 289 * burst was received. SYNERR is raised if the AFRAME or BFRAME status 290 * bits are set during the minute, FMTERR is raised if the AFORMAT or 291 * BFORMAT status bits are set, DECERR is raised if the DECODE status 292 * bit is set and TSPERR is raised if the STAMP status bit is set. 293 */ 294 #define SYNERR 0x01 /* frame sync error */ 295 #define FMTERR 0x02 /* data format error */ 296 #define DECERR 0x04 /* data decoding error */ 297 #define TSPERR 0x08 /* insufficient data */ 298 299 #ifdef HAVE_AUDIO 300 /* 301 * Maximum-likelihood UART structure. There are eight of these 302 * corresponding to the number of phases. 303 */ 304 struct surv { 305 l_fp cstamp; /* last bit timestamp */ 306 double shift[12]; /* sample shift register */ 307 double span; /* shift register envelope span */ 308 double dist; /* sample distance */ 309 int uart; /* decoded character */ 310 }; 311 #endif /* HAVE_AUDIO */ 312 313 #ifdef ICOM 314 /* 315 * CHU station structure. There are three of these corresponding to the 316 * three frequencies. 317 */ 318 struct xmtr { 319 double integ[ISTAGE]; /* circular integrator */ 320 double metric; /* integrator sum */ 321 int iptr; /* integrator pointer */ 322 int probe; /* dwells since last probe */ 323 }; 324 #endif /* ICOM */ 325 326 /* 327 * CHU unit control structure 328 */ 329 struct chuunit { 330 u_char decode[20][16]; /* maximum-likelihood decoding matrix */ 331 l_fp cstamp[BURST]; /* character timestamps */ 332 l_fp tstamp[MAXSTAGE]; /* timestamp samples */ 333 l_fp timestamp; /* current buffer timestamp */ 334 l_fp laststamp; /* last buffer timestamp */ 335 l_fp charstamp; /* character time as a l_fp */ 336 int second; /* counts the seconds of the minute */ 337 int errflg; /* error flags */ 338 int status; /* status bits */ 339 char ident[5]; /* station ID and channel */ 340 #ifdef ICOM 341 int fd_icom; /* ICOM file descriptor */ 342 int chan; /* radio channel */ 343 int dwell; /* dwell cycle */ 344 struct xmtr xmtr[NCHAN]; /* station metric */ 345 #endif /* ICOM */ 346 347 /* 348 * Character burst variables 349 */ 350 int cbuf[BURST]; /* character buffer */ 351 int ntstamp; /* number of timestamp samples */ 352 int ndx; /* buffer start index */ 353 int prevsec; /* previous burst second */ 354 int burdist; /* burst distance */ 355 int syndist; /* sync distance */ 356 int burstcnt; /* format A bursts this minute */ 357 double maxsignal; /* signal level (modem only) */ 358 int gain; /* codec gain (modem only) */ 359 360 /* 361 * Format particulars 362 */ 363 int leap; /* leap/dut code */ 364 int dut; /* UTC1 correction */ 365 int tai; /* TAI - UTC correction */ 366 int dst; /* Canadian DST code */ 367 368 #ifdef HAVE_AUDIO 369 /* 370 * Audio codec variables 371 */ 372 int fd_audio; /* audio port file descriptor */ 373 double comp[SIZE]; /* decompanding table */ 374 int port; /* codec port */ 375 int mongain; /* codec monitor gain */ 376 int clipcnt; /* sample clip count */ 377 int seccnt; /* second interval counter */ 378 379 /* 380 * Modem variables 381 */ 382 l_fp tick; /* audio sample increment */ 383 double bpf[9]; /* IIR bandpass filter */ 384 double disc[LAG]; /* discriminator shift register */ 385 double lpf[27]; /* FIR lowpass filter */ 386 double monitor; /* audio monitor */ 387 int discptr; /* discriminator pointer */ 388 389 /* 390 * Maximum-likelihood UART variables 391 */ 392 double baud; /* baud interval */ 393 struct surv surv[8]; /* UART survivor structures */ 394 int decptr; /* decode pointer */ 395 int decpha; /* decode phase */ 396 int dbrk; /* holdoff counter */ 397 #endif /* HAVE_AUDIO */ 398 }; 399 400 /* 401 * Function prototypes 402 */ 403 static int chu_start (int, struct peer *); 404 static void chu_shutdown (int, struct peer *); 405 static void chu_receive (struct recvbuf *); 406 static void chu_second (int, struct peer *); 407 static void chu_poll (int, struct peer *); 408 409 /* 410 * More function prototypes 411 */ 412 static void chu_decode (struct peer *, int, l_fp); 413 static void chu_burst (struct peer *); 414 static void chu_clear (struct peer *); 415 static void chu_a (struct peer *, int); 416 static void chu_b (struct peer *, int); 417 static int chu_dist (int, int); 418 static double chu_major (struct peer *); 419 #ifdef HAVE_AUDIO 420 static void chu_uart (struct surv *, double); 421 static void chu_rf (struct peer *, double); 422 static void chu_gain (struct peer *); 423 static void chu_audio_receive (struct recvbuf *rbufp); 424 #endif /* HAVE_AUDIO */ 425 #ifdef ICOM 426 static int chu_newchan (struct peer *, double); 427 #endif /* ICOM */ 428 static void chu_serial_receive (struct recvbuf *rbufp); 429 430 /* 431 * Global variables 432 */ 433 static char hexchar[] = "0123456789abcdef_*="; 434 435 #ifdef ICOM 436 /* 437 * Note the tuned frequencies are 1 kHz higher than the carrier. CHU 438 * transmits on USB with carrier so we can use AM and the narrow SSB 439 * filter. 440 */ 441 static double qsy[NCHAN] = {3.330, 7.850, 14.670}; /* freq (MHz) */ 442 #endif /* ICOM */ 443 444 /* 445 * Transfer vector 446 */ 447 struct refclock refclock_chu = { 448 chu_start, /* start up driver */ 449 chu_shutdown, /* shut down driver */ 450 chu_poll, /* transmit poll message */ 451 noentry, /* not used (old chu_control) */ 452 noentry, /* initialize driver (not used) */ 453 noentry, /* not used (old chu_buginfo) */ 454 chu_second /* housekeeping timer */ 455 }; 456 457 458 /* 459 * chu_start - open the devices and initialize data for processing 460 */ 461 static int 462 chu_start( 463 int unit, /* instance number (not used) */ 464 struct peer *peer /* peer structure pointer */ 465 ) 466 { 467 struct chuunit *up; 468 struct refclockproc *pp; 469 char device[20]; /* device name */ 470 int fd; /* file descriptor */ 471 #ifdef ICOM 472 int temp; 473 #endif /* ICOM */ 474 #ifdef HAVE_AUDIO 475 int fd_audio; /* audio port file descriptor */ 476 int i; /* index */ 477 double step; /* codec adjustment */ 478 479 /* 480 * Open audio device. Don't complain if not there. 481 */ 482 fd_audio = audio_init(DEVICE_AUDIO, AUDIO_BUFSIZ, unit); 483 #ifdef DEBUG 484 if (fd_audio > 0 && debug) 485 audio_show(); 486 #endif 487 488 /* 489 * If audio is unavailable, Open serial port in raw mode. 490 */ 491 if (fd_audio > 0) { 492 fd = fd_audio; 493 } else { 494 snprintf(device, sizeof(device), DEVICE, unit); 495 fd = refclock_open(device, SPEED232, LDISC_RAW); 496 } 497 #else /* HAVE_AUDIO */ 498 499 /* 500 * Open serial port in raw mode. 501 */ 502 snprintf(device, sizeof(device), DEVICE, unit); 503 fd = refclock_open(device, SPEED232, LDISC_RAW); 504 #endif /* HAVE_AUDIO */ 505 if (fd <= 0) 506 return (0); 507 508 /* 509 * Allocate and initialize unit structure 510 */ 511 up = emalloc(sizeof(*up)); 512 memset(up, 0, sizeof(*up)); 513 pp = peer->procptr; 514 pp->unitptr = (caddr_t)up; 515 pp->io.clock_recv = chu_receive; 516 pp->io.srcclock = (caddr_t)peer; 517 pp->io.datalen = 0; 518 pp->io.fd = fd; 519 if (!io_addclock(&pp->io)) { 520 close(fd); 521 pp->io.fd = -1; 522 free(up); 523 pp->unitptr = NULL; 524 return (0); 525 } 526 527 /* 528 * Initialize miscellaneous variables 529 */ 530 peer->precision = PRECISION; 531 pp->clockdesc = DESCRIPTION; 532 strcpy(up->ident, "CHU"); 533 memcpy(&pp->refid, up->ident, 4); 534 DTOLFP(CHAR, &up->charstamp); 535 #ifdef HAVE_AUDIO 536 537 /* 538 * The companded samples are encoded sign-magnitude. The table 539 * contains all the 256 values in the interest of speed. We do 540 * this even if the audio codec is not available. C'est la lazy. 541 */ 542 up->fd_audio = fd_audio; 543 up->gain = 127; 544 up->comp[0] = up->comp[OFFSET] = 0.; 545 up->comp[1] = 1; up->comp[OFFSET + 1] = -1.; 546 up->comp[2] = 3; up->comp[OFFSET + 2] = -3.; 547 step = 2.; 548 for (i = 3; i < OFFSET; i++) { 549 up->comp[i] = up->comp[i - 1] + step; 550 up->comp[OFFSET + i] = -up->comp[i]; 551 if (i % 16 == 0) 552 step *= 2.; 553 } 554 DTOLFP(1. / SECOND, &up->tick); 555 #endif /* HAVE_AUDIO */ 556 #ifdef ICOM 557 temp = 0; 558 #ifdef DEBUG 559 if (debug > 1) 560 temp = P_TRACE; 561 #endif 562 if (peer->ttl > 0) { 563 if (peer->ttl & 0x80) 564 up->fd_icom = icom_init("/dev/icom", B1200, 565 temp); 566 else 567 up->fd_icom = icom_init("/dev/icom", B9600, 568 temp); 569 } 570 if (up->fd_icom > 0) { 571 if (chu_newchan(peer, 0) != 0) { 572 msyslog(LOG_NOTICE, "icom: radio not found"); 573 close(up->fd_icom); 574 up->fd_icom = 0; 575 } else { 576 msyslog(LOG_NOTICE, "icom: autotune enabled"); 577 } 578 } 579 #endif /* ICOM */ 580 return (1); 581 } 582 583 584 /* 585 * chu_shutdown - shut down the clock 586 */ 587 static void 588 chu_shutdown( 589 int unit, /* instance number (not used) */ 590 struct peer *peer /* peer structure pointer */ 591 ) 592 { 593 struct chuunit *up; 594 struct refclockproc *pp; 595 596 pp = peer->procptr; 597 up = (struct chuunit *)pp->unitptr; 598 if (up == NULL) 599 return; 600 601 io_closeclock(&pp->io); 602 #ifdef ICOM 603 if (up->fd_icom > 0) 604 close(up->fd_icom); 605 #endif /* ICOM */ 606 free(up); 607 } 608 609 610 /* 611 * chu_receive - receive data from the audio or serial device 612 */ 613 static void 614 chu_receive( 615 struct recvbuf *rbufp /* receive buffer structure pointer */ 616 ) 617 { 618 #ifdef HAVE_AUDIO 619 struct chuunit *up; 620 struct refclockproc *pp; 621 struct peer *peer; 622 623 peer = (struct peer *)rbufp->recv_srcclock; 624 pp = peer->procptr; 625 up = (struct chuunit *)pp->unitptr; 626 627 /* 628 * If the audio codec is warmed up, the buffer contains codec 629 * samples which need to be demodulated and decoded into CHU 630 * characters using the software UART. Otherwise, the buffer 631 * contains CHU characters from the serial port, so the software 632 * UART is bypassed. In this case the CPU will probably run a 633 * few degrees cooler. 634 */ 635 if (up->fd_audio > 0) 636 chu_audio_receive(rbufp); 637 else 638 chu_serial_receive(rbufp); 639 #else 640 chu_serial_receive(rbufp); 641 #endif /* HAVE_AUDIO */ 642 } 643 644 645 #ifdef HAVE_AUDIO 646 /* 647 * chu_audio_receive - receive data from the audio device 648 */ 649 static void 650 chu_audio_receive( 651 struct recvbuf *rbufp /* receive buffer structure pointer */ 652 ) 653 { 654 struct chuunit *up; 655 struct refclockproc *pp; 656 struct peer *peer; 657 658 double sample; /* codec sample */ 659 u_char *dpt; /* buffer pointer */ 660 int bufcnt; /* buffer counter */ 661 l_fp ltemp; /* l_fp temp */ 662 663 peer = (struct peer *)rbufp->recv_srcclock; 664 pp = peer->procptr; 665 up = (struct chuunit *)pp->unitptr; 666 667 /* 668 * Main loop - read until there ain't no more. Note codec 669 * samples are bit-inverted. 670 */ 671 DTOLFP((double)rbufp->recv_length / SECOND, <emp); 672 L_SUB(&rbufp->recv_time, <emp); 673 up->timestamp = rbufp->recv_time; 674 dpt = rbufp->recv_buffer; 675 for (bufcnt = 0; bufcnt < rbufp->recv_length; bufcnt++) { 676 sample = up->comp[~*dpt++ & 0xff]; 677 678 /* 679 * Clip noise spikes greater than MAXAMP. If no clips, 680 * increase the gain a tad; if the clips are too high, 681 * decrease a tad. 682 */ 683 if (sample > MAXAMP) { 684 sample = MAXAMP; 685 up->clipcnt++; 686 } else if (sample < -MAXAMP) { 687 sample = -MAXAMP; 688 up->clipcnt++; 689 } 690 chu_rf(peer, sample); 691 L_ADD(&up->timestamp, &up->tick); 692 693 /* 694 * Once each second ride gain. 695 */ 696 up->seccnt = (up->seccnt + 1) % SECOND; 697 if (up->seccnt == 0) { 698 chu_gain(peer); 699 } 700 } 701 702 /* 703 * Set the input port and monitor gain for the next buffer. 704 */ 705 if (pp->sloppyclockflag & CLK_FLAG2) 706 up->port = 2; 707 else 708 up->port = 1; 709 if (pp->sloppyclockflag & CLK_FLAG3) 710 up->mongain = MONGAIN; 711 else 712 up->mongain = 0; 713 } 714 715 716 /* 717 * chu_rf - filter and demodulate the FSK signal 718 * 719 * This routine implements a 300-baud Bell 103 modem with mark 2225 Hz 720 * and space 2025 Hz. It uses a bandpass filter followed by a soft 721 * limiter, FM discriminator and lowpass filter. A maximum-likelihood 722 * decoder samples the baseband signal at eight times the baud rate and 723 * detects the start bit of each character. 724 * 725 * The filters are built for speed, which explains the rather clumsy 726 * code. Hopefully, the compiler will efficiently implement the move- 727 * and-muiltiply-and-add operations. 728 */ 729 static void 730 chu_rf( 731 struct peer *peer, /* peer structure pointer */ 732 double sample /* analog sample */ 733 ) 734 { 735 struct refclockproc *pp; 736 struct chuunit *up; 737 struct surv *sp; 738 739 /* 740 * Local variables 741 */ 742 double signal; /* bandpass signal */ 743 double limit; /* limiter signal */ 744 double disc; /* discriminator signal */ 745 double lpf; /* lowpass signal */ 746 double dist; /* UART signal distance */ 747 int i, j; 748 749 pp = peer->procptr; 750 up = (struct chuunit *)pp->unitptr; 751 752 /* 753 * Bandpass filter. 4th-order elliptic, 500-Hz bandpass centered 754 * at 2125 Hz. Passband ripple 0.3 dB, stopband ripple 50 dB, 755 * phase delay 0.24 ms. 756 */ 757 signal = (up->bpf[8] = up->bpf[7]) * 5.844676e-01; 758 signal += (up->bpf[7] = up->bpf[6]) * 4.884860e-01; 759 signal += (up->bpf[6] = up->bpf[5]) * 2.704384e+00; 760 signal += (up->bpf[5] = up->bpf[4]) * 1.645032e+00; 761 signal += (up->bpf[4] = up->bpf[3]) * 4.644557e+00; 762 signal += (up->bpf[3] = up->bpf[2]) * 1.879165e+00; 763 signal += (up->bpf[2] = up->bpf[1]) * 3.522634e+00; 764 signal += (up->bpf[1] = up->bpf[0]) * 7.315738e-01; 765 up->bpf[0] = sample - signal; 766 signal = up->bpf[0] * 6.176213e-03 767 + up->bpf[1] * 3.156599e-03 768 + up->bpf[2] * 7.567487e-03 769 + up->bpf[3] * 4.344580e-03 770 + up->bpf[4] * 1.190128e-02 771 + up->bpf[5] * 4.344580e-03 772 + up->bpf[6] * 7.567487e-03 773 + up->bpf[7] * 3.156599e-03 774 + up->bpf[8] * 6.176213e-03; 775 776 up->monitor = signal / 4.; /* note monitor after filter */ 777 778 /* 779 * Soft limiter/discriminator. The 11-sample discriminator lag 780 * interval corresponds to three cycles of 2125 Hz, which 781 * requires the sample frequency to be 2125 * 11 / 3 = 7791.7 782 * Hz. The discriminator output varies +-0.5 interval for input 783 * frequency 2025-2225 Hz. However, we don't get to sample at 784 * this frequency, so the discriminator output is biased. Life 785 * at 8000 Hz sucks. 786 */ 787 limit = signal; 788 if (limit > LIMIT) 789 limit = LIMIT; 790 else if (limit < -LIMIT) 791 limit = -LIMIT; 792 disc = up->disc[up->discptr] * -limit; 793 up->disc[up->discptr] = limit; 794 up->discptr = (up->discptr + 1 ) % LAG; 795 if (disc >= 0) 796 disc = SQRT(disc); 797 else 798 disc = -SQRT(-disc); 799 800 /* 801 * Lowpass filter. Raised cosine FIR, Ts = 1 / 300, beta = 0.1. 802 */ 803 lpf = (up->lpf[26] = up->lpf[25]) * 2.538771e-02; 804 lpf += (up->lpf[25] = up->lpf[24]) * 1.084671e-01; 805 lpf += (up->lpf[24] = up->lpf[23]) * 2.003159e-01; 806 lpf += (up->lpf[23] = up->lpf[22]) * 2.985303e-01; 807 lpf += (up->lpf[22] = up->lpf[21]) * 4.003697e-01; 808 lpf += (up->lpf[21] = up->lpf[20]) * 5.028552e-01; 809 lpf += (up->lpf[20] = up->lpf[19]) * 6.028795e-01; 810 lpf += (up->lpf[19] = up->lpf[18]) * 6.973249e-01; 811 lpf += (up->lpf[18] = up->lpf[17]) * 7.831828e-01; 812 lpf += (up->lpf[17] = up->lpf[16]) * 8.576717e-01; 813 lpf += (up->lpf[16] = up->lpf[15]) * 9.183463e-01; 814 lpf += (up->lpf[15] = up->lpf[14]) * 9.631951e-01; 815 lpf += (up->lpf[14] = up->lpf[13]) * 9.907208e-01; 816 lpf += (up->lpf[13] = up->lpf[12]) * 1.000000e+00; 817 lpf += (up->lpf[12] = up->lpf[11]) * 9.907208e-01; 818 lpf += (up->lpf[11] = up->lpf[10]) * 9.631951e-01; 819 lpf += (up->lpf[10] = up->lpf[9]) * 9.183463e-01; 820 lpf += (up->lpf[9] = up->lpf[8]) * 8.576717e-01; 821 lpf += (up->lpf[8] = up->lpf[7]) * 7.831828e-01; 822 lpf += (up->lpf[7] = up->lpf[6]) * 6.973249e-01; 823 lpf += (up->lpf[6] = up->lpf[5]) * 6.028795e-01; 824 lpf += (up->lpf[5] = up->lpf[4]) * 5.028552e-01; 825 lpf += (up->lpf[4] = up->lpf[3]) * 4.003697e-01; 826 lpf += (up->lpf[3] = up->lpf[2]) * 2.985303e-01; 827 lpf += (up->lpf[2] = up->lpf[1]) * 2.003159e-01; 828 lpf += (up->lpf[1] = up->lpf[0]) * 1.084671e-01; 829 lpf += up->lpf[0] = disc * 2.538771e-02; 830 831 /* 832 * Maximum-likelihood decoder. The UART updates each of the 833 * eight survivors and determines the span, slice level and 834 * tentative decoded character. Valid 11-bit characters are 835 * framed so that bit 10 and bit 11 (stop bits) are mark and bit 836 * 1 (start bit) is space. When a valid character is found, the 837 * survivor with maximum distance determines the final decoded 838 * character. 839 */ 840 up->baud += 1. / SECOND; 841 if (up->baud > 1. / (BAUD * 8.)) { 842 up->baud -= 1. / (BAUD * 8.); 843 up->decptr = (up->decptr + 1) % 8; 844 sp = &up->surv[up->decptr]; 845 sp->cstamp = up->timestamp; 846 chu_uart(sp, -lpf * AGAIN); 847 if (up->dbrk > 0) { 848 up->dbrk--; 849 if (up->dbrk > 0) 850 return; 851 852 up->decpha = up->decptr; 853 } 854 if (up->decptr != up->decpha) 855 return; 856 857 dist = 0; 858 j = -1; 859 for (i = 0; i < 8; i++) { 860 861 /* 862 * The timestamp is taken at the last bit, so 863 * for correct decoding we reqire sufficient 864 * span and correct start bit and two stop bits. 865 */ 866 if ((up->surv[i].uart & 0x601) != 0x600 || 867 up->surv[i].span < SPAN) 868 continue; 869 870 if (up->surv[i].dist > dist) { 871 dist = up->surv[i].dist; 872 j = i; 873 } 874 } 875 if (j < 0) 876 return; 877 878 /* 879 * Process the character, then blank the decoder until 880 * the end of the next character.This sets the decoding 881 * phase of the entire burst from the phase of the first 882 * character. 883 */ 884 up->maxsignal = up->surv[j].span; 885 chu_decode(peer, (up->surv[j].uart >> 1) & 0xff, 886 up->surv[j].cstamp); 887 up->dbrk = 88; 888 } 889 } 890 891 892 /* 893 * chu_uart - maximum-likelihood UART 894 * 895 * This routine updates a shift register holding the last 11 envelope 896 * samples. It then computes the slice level and span over these samples 897 * and determines the tentative data bits and distance. The calling 898 * program selects over the last eight survivors the one with maximum 899 * distance to determine the decoded character. 900 */ 901 static void 902 chu_uart( 903 struct surv *sp, /* survivor structure pointer */ 904 double sample /* baseband signal */ 905 ) 906 { 907 double es_max, es_min; /* max/min envelope */ 908 double slice; /* slice level */ 909 double dist; /* distance */ 910 double dtemp; 911 int i; 912 913 /* 914 * Save the sample and shift right. At the same time, measure 915 * the maximum and minimum over all eleven samples. 916 */ 917 es_max = -1e6; 918 es_min = 1e6; 919 sp->shift[0] = sample; 920 for (i = 11; i > 0; i--) { 921 sp->shift[i] = sp->shift[i - 1]; 922 if (sp->shift[i] > es_max) 923 es_max = sp->shift[i]; 924 if (sp->shift[i] < es_min) 925 es_min = sp->shift[i]; 926 } 927 928 /* 929 * Determine the span as the maximum less the minimum and the 930 * slice level as the minimum plus a fraction of the span. Note 931 * the slight bias toward mark to correct for the modem tendency 932 * to make more mark than space errors. Compute the distance on 933 * the assumption the last two bits must be mark, the first 934 * space and the rest either mark or space. 935 */ 936 sp->span = es_max - es_min; 937 slice = es_min + .45 * sp->span; 938 dist = 0; 939 sp->uart = 0; 940 for (i = 1; i < 12; i++) { 941 sp->uart <<= 1; 942 dtemp = sp->shift[i]; 943 if (dtemp > slice) 944 sp->uart |= 0x1; 945 if (i == 1 || i == 2) { 946 dist += dtemp - es_min; 947 } else if (i == 11) { 948 dist += es_max - dtemp; 949 } else { 950 if (dtemp > slice) 951 dist += dtemp - es_min; 952 else 953 dist += es_max - dtemp; 954 } 955 } 956 sp->dist = dist / (11 * sp->span); 957 } 958 #endif /* HAVE_AUDIO */ 959 960 961 /* 962 * chu_serial_receive - receive data from the serial device 963 */ 964 static void 965 chu_serial_receive( 966 struct recvbuf *rbufp /* receive buffer structure pointer */ 967 ) 968 { 969 struct chuunit *up; 970 struct refclockproc *pp; 971 struct peer *peer; 972 973 u_char *dpt; /* receive buffer pointer */ 974 975 peer = (struct peer *)rbufp->recv_srcclock; 976 pp = peer->procptr; 977 up = (struct chuunit *)pp->unitptr; 978 979 dpt = (u_char *)&rbufp->recv_space; 980 chu_decode(peer, *dpt, rbufp->recv_time); 981 } 982 983 984 /* 985 * chu_decode - decode the character data 986 */ 987 static void 988 chu_decode( 989 struct peer *peer, /* peer structure pointer */ 990 int hexhex, /* data character */ 991 l_fp cstamp /* data character timestamp */ 992 ) 993 { 994 struct refclockproc *pp; 995 struct chuunit *up; 996 997 l_fp tstmp; /* timestamp temp */ 998 double dtemp; 999 1000 pp = peer->procptr; 1001 up = (struct chuunit *)pp->unitptr; 1002 1003 /* 1004 * If the interval since the last character is greater than the 1005 * longest burst, process the last burst and start a new one. If 1006 * the interval is less than this but greater than two 1007 * characters, consider this a noise burst and reject it. 1008 */ 1009 tstmp = up->timestamp; 1010 if (L_ISZERO(&up->laststamp)) 1011 up->laststamp = up->timestamp; 1012 L_SUB(&tstmp, &up->laststamp); 1013 up->laststamp = up->timestamp; 1014 LFPTOD(&tstmp, dtemp); 1015 if (dtemp > BURST * CHAR) { 1016 chu_burst(peer); 1017 up->ndx = 0; 1018 } else if (dtemp > 2.5 * CHAR) { 1019 up->ndx = 0; 1020 } 1021 1022 /* 1023 * Append the character to the current burst and append the 1024 * character timestamp to the timestamp list. 1025 */ 1026 if (up->ndx < BURST) { 1027 up->cbuf[up->ndx] = hexhex & 0xff; 1028 up->cstamp[up->ndx] = cstamp; 1029 up->ndx++; 1030 1031 } 1032 } 1033 1034 1035 /* 1036 * chu_burst - search for valid burst format 1037 */ 1038 static void 1039 chu_burst( 1040 struct peer *peer 1041 ) 1042 { 1043 struct chuunit *up; 1044 struct refclockproc *pp; 1045 1046 int i; 1047 1048 pp = peer->procptr; 1049 up = (struct chuunit *)pp->unitptr; 1050 1051 /* 1052 * Correlate a block of five characters with the next block of 1053 * five characters. The burst distance is defined as the number 1054 * of bits that match in the two blocks for format A and that 1055 * match the inverse for format B. 1056 */ 1057 if (up->ndx < MINCHAR) { 1058 up->status |= RUNT; 1059 return; 1060 } 1061 up->burdist = 0; 1062 for (i = 0; i < 5 && i < up->ndx - 5; i++) 1063 up->burdist += chu_dist(up->cbuf[i], up->cbuf[i + 5]); 1064 1065 /* 1066 * If the burst distance is at least MINDIST, this must be a 1067 * format A burst; if the value is not greater than -MINDIST, it 1068 * must be a format B burst. If the B burst is perfect, we 1069 * believe it; otherwise, it is a noise burst and of no use to 1070 * anybody. 1071 */ 1072 if (up->burdist >= MINDIST) { 1073 chu_a(peer, up->ndx); 1074 } else if (up->burdist <= -MINDIST) { 1075 chu_b(peer, up->ndx); 1076 } else { 1077 up->status |= NOISE; 1078 return; 1079 } 1080 1081 /* 1082 * If this is a valid burst, wait a guard time of ten seconds to 1083 * allow for more bursts, then arm the poll update routine to 1084 * process the minute. Don't do this if this is called from the 1085 * timer interrupt routine. 1086 */ 1087 if (peer->outdate != current_time) 1088 peer->nextdate = current_time + 10; 1089 } 1090 1091 1092 /* 1093 * chu_b - decode format B burst 1094 */ 1095 static void 1096 chu_b( 1097 struct peer *peer, 1098 int nchar 1099 ) 1100 { 1101 struct refclockproc *pp; 1102 struct chuunit *up; 1103 1104 u_char code[11]; /* decoded timecode */ 1105 char tbuf[80]; /* trace buffer */ 1106 char * p; 1107 size_t chars; 1108 size_t cb; 1109 int i; 1110 1111 pp = peer->procptr; 1112 up = (struct chuunit *)pp->unitptr; 1113 1114 /* 1115 * In a format B burst, a character is considered valid only if 1116 * the first occurence matches the last occurence. The burst is 1117 * considered valid only if all characters are valid; that is, 1118 * only if the distance is 40. Note that once a valid frame has 1119 * been found errors are ignored. 1120 */ 1121 snprintf(tbuf, sizeof(tbuf), "chuB %04x %4.0f %2d %2d ", 1122 up->status, up->maxsignal, nchar, -up->burdist); 1123 cb = sizeof(tbuf); 1124 p = tbuf; 1125 for (i = 0; i < nchar; i++) { 1126 chars = strlen(p); 1127 if (cb < chars + 1) { 1128 msyslog(LOG_ERR, "chu_b() fatal out buffer"); 1129 exit(1); 1130 } 1131 cb -= chars; 1132 p += chars; 1133 snprintf(p, cb, "%02x", up->cbuf[i]); 1134 } 1135 if (pp->sloppyclockflag & CLK_FLAG4) 1136 record_clock_stats(&peer->srcadr, tbuf); 1137 #ifdef DEBUG 1138 if (debug) 1139 printf("%s\n", tbuf); 1140 #endif 1141 if (up->burdist > -40) { 1142 up->status |= BFRAME; 1143 return; 1144 } 1145 1146 /* 1147 * Convert the burst data to internal format. Don't bother with 1148 * the timestamps. 1149 */ 1150 for (i = 0; i < 5; i++) { 1151 code[2 * i] = hexchar[up->cbuf[i] & 0xf]; 1152 code[2 * i + 1] = hexchar[(up->cbuf[i] >> 1153 4) & 0xf]; 1154 } 1155 if (sscanf((char *)code, "%1x%1d%4d%2d%2x", &up->leap, &up->dut, 1156 &pp->year, &up->tai, &up->dst) != 5) { 1157 up->status |= BFORMAT; 1158 return; 1159 } 1160 up->status |= BVALID; 1161 if (up->leap & 0x8) 1162 up->dut = -up->dut; 1163 } 1164 1165 1166 /* 1167 * chu_a - decode format A burst 1168 */ 1169 static void 1170 chu_a( 1171 struct peer *peer, 1172 int nchar 1173 ) 1174 { 1175 struct refclockproc *pp; 1176 struct chuunit *up; 1177 1178 char tbuf[80]; /* trace buffer */ 1179 char * p; 1180 size_t chars; 1181 size_t cb; 1182 l_fp offset; /* timestamp offset */ 1183 int val; /* distance */ 1184 int temp; 1185 int i, j, k; 1186 1187 pp = peer->procptr; 1188 up = (struct chuunit *)pp->unitptr; 1189 1190 /* 1191 * Determine correct burst phase. There are three cases 1192 * corresponding to in-phase, one character early or one 1193 * character late. These cases are distinguished by the position 1194 * of the framing digits 0x6 at positions 0 and 5 and 0x3 at 1195 * positions 4 and 9. The correct phase is when the distance 1196 * relative to the framing digits is maximum. The burst is valid 1197 * only if the maximum distance is at least MINSYNC. 1198 */ 1199 up->syndist = k = 0; 1200 val = -16; 1201 for (i = -1; i < 2; i++) { 1202 temp = up->cbuf[i + 4] & 0xf; 1203 if (i >= 0) 1204 temp |= (up->cbuf[i] & 0xf) << 4; 1205 val = chu_dist(temp, 0x63); 1206 temp = (up->cbuf[i + 5] & 0xf) << 4; 1207 if (i + 9 < nchar) 1208 temp |= up->cbuf[i + 9] & 0xf; 1209 val += chu_dist(temp, 0x63); 1210 if (val > up->syndist) { 1211 up->syndist = val; 1212 k = i; 1213 } 1214 } 1215 1216 /* 1217 * Extract the second number; it must be in the range 2 through 1218 * 9 and the two repititions must be the same. 1219 */ 1220 temp = (up->cbuf[k + 4] >> 4) & 0xf; 1221 if (temp < 2 || temp > 9 || k + 9 >= nchar || temp != 1222 ((up->cbuf[k + 9] >> 4) & 0xf)) 1223 temp = 0; 1224 snprintf(tbuf, sizeof(tbuf), 1225 "chuA %04x %4.0f %2d %2d %2d %2d %1d ", up->status, 1226 up->maxsignal, nchar, up->burdist, k, up->syndist, 1227 temp); 1228 cb = sizeof(tbuf); 1229 p = tbuf; 1230 for (i = 0; i < nchar; i++) { 1231 chars = strlen(p); 1232 if (cb < chars + 1) { 1233 msyslog(LOG_ERR, "chu_a() fatal out buffer"); 1234 exit(1); 1235 } 1236 cb -= chars; 1237 p += chars; 1238 snprintf(p, cb, "%02x", up->cbuf[i]); 1239 } 1240 if (pp->sloppyclockflag & CLK_FLAG4) 1241 record_clock_stats(&peer->srcadr, tbuf); 1242 #ifdef DEBUG 1243 if (debug) 1244 printf("%s\n", tbuf); 1245 #endif 1246 if (up->syndist < MINSYNC) { 1247 up->status |= AFRAME; 1248 return; 1249 } 1250 1251 /* 1252 * A valid burst requires the first seconds number to match the 1253 * last seconds number. If so, the burst timestamps are 1254 * corrected to the current minute and saved for later 1255 * processing. In addition, the seconds decode is advanced from 1256 * the previous burst to the current one. 1257 */ 1258 if (temp == 0) { 1259 up->status |= AFORMAT; 1260 } else { 1261 up->status |= AVALID; 1262 up->second = pp->second = 30 + temp; 1263 offset.l_ui = 30 + temp; 1264 offset.l_f = 0; 1265 i = 0; 1266 if (k < 0) 1267 offset = up->charstamp; 1268 else if (k > 0) 1269 i = 1; 1270 for (; i < nchar && i < k + 10; i++) { 1271 up->tstamp[up->ntstamp] = up->cstamp[i]; 1272 L_SUB(&up->tstamp[up->ntstamp], &offset); 1273 L_ADD(&offset, &up->charstamp); 1274 if (up->ntstamp < MAXSTAGE - 1) 1275 up->ntstamp++; 1276 } 1277 while (temp > up->prevsec) { 1278 for (j = 15; j > 0; j--) { 1279 up->decode[9][j] = up->decode[9][j - 1]; 1280 up->decode[19][j] = 1281 up->decode[19][j - 1]; 1282 } 1283 up->decode[9][j] = up->decode[19][j] = 0; 1284 up->prevsec++; 1285 } 1286 } 1287 1288 /* 1289 * Stash the data in the decoding matrix. 1290 */ 1291 i = -(2 * k); 1292 for (j = 0; j < nchar; j++) { 1293 if (i < 0 || i > 18) { 1294 i += 2; 1295 continue; 1296 } 1297 up->decode[i][up->cbuf[j] & 0xf]++; 1298 i++; 1299 up->decode[i][(up->cbuf[j] >> 4) & 0xf]++; 1300 i++; 1301 } 1302 up->burstcnt++; 1303 } 1304 1305 1306 /* 1307 * chu_poll - called by the transmit procedure 1308 */ 1309 static void 1310 chu_poll( 1311 int unit, 1312 struct peer *peer /* peer structure pointer */ 1313 ) 1314 { 1315 struct refclockproc *pp; 1316 1317 pp = peer->procptr; 1318 pp->polls++; 1319 } 1320 1321 1322 /* 1323 * chu_second - process minute data 1324 */ 1325 static void 1326 chu_second( 1327 int unit, 1328 struct peer *peer /* peer structure pointer */ 1329 ) 1330 { 1331 struct refclockproc *pp; 1332 struct chuunit *up; 1333 l_fp offset; 1334 char synchar, qual, leapchar; 1335 int minset, i; 1336 double dtemp; 1337 1338 pp = peer->procptr; 1339 up = (struct chuunit *)pp->unitptr; 1340 1341 /* 1342 * This routine is called once per minute to process the 1343 * accumulated burst data. We do a bit of fancy footwork so that 1344 * this doesn't run while burst data are being accumulated. 1345 */ 1346 up->second = (up->second + 1) % 60; 1347 if (up->second != 0) 1348 return; 1349 1350 /* 1351 * Process the last burst, if still in the burst buffer. 1352 * If the minute contains a valid B frame with sufficient A 1353 * frame metric, it is considered valid. However, the timecode 1354 * is sent to clockstats even if invalid. 1355 */ 1356 chu_burst(peer); 1357 minset = ((current_time - peer->update) + 30) / 60; 1358 dtemp = chu_major(peer); 1359 qual = 0; 1360 if (up->status & (BFRAME | AFRAME)) 1361 qual |= SYNERR; 1362 if (up->status & (BFORMAT | AFORMAT)) 1363 qual |= FMTERR; 1364 if (up->status & DECODE) 1365 qual |= DECERR; 1366 if (up->status & STAMP) 1367 qual |= TSPERR; 1368 if (up->status & BVALID && dtemp >= MINMETRIC) 1369 up->status |= INSYNC; 1370 synchar = leapchar = ' '; 1371 if (!(up->status & INSYNC)) { 1372 pp->leap = LEAP_NOTINSYNC; 1373 synchar = '?'; 1374 } else if (up->leap & 0x2) { 1375 pp->leap = LEAP_ADDSECOND; 1376 leapchar = 'L'; 1377 } else if (up->leap & 0x4) { 1378 pp->leap = LEAP_DELSECOND; 1379 leapchar = 'l'; 1380 } else { 1381 pp->leap = LEAP_NOWARNING; 1382 } 1383 snprintf(pp->a_lastcode, sizeof(pp->a_lastcode), 1384 "%c%1X %04d %03d %02d:%02d:%02d %c%x %+d %d %d %s %.0f %d", 1385 synchar, qual, pp->year, pp->day, pp->hour, pp->minute, 1386 pp->second, leapchar, up->dst, up->dut, minset, up->gain, 1387 up->ident, dtemp, up->ntstamp); 1388 pp->lencode = strlen(pp->a_lastcode); 1389 1390 /* 1391 * If in sync and the signal metric is above threshold, the 1392 * timecode is ipso fatso valid and can be selected to 1393 * discipline the clock. 1394 */ 1395 if (up->status & INSYNC && !(up->status & (DECODE | STAMP)) && 1396 dtemp > MINMETRIC) { 1397 if (!clocktime(pp->day, pp->hour, pp->minute, 0, GMT, 1398 up->tstamp[0].l_ui, &pp->yearstart, &offset.l_ui)) { 1399 up->errflg = CEVNT_BADTIME; 1400 } else { 1401 offset.l_uf = 0; 1402 for (i = 0; i < up->ntstamp; i++) 1403 refclock_process_offset(pp, offset, 1404 up->tstamp[i], PDELAY + 1405 pp->fudgetime1); 1406 pp->lastref = up->timestamp; 1407 refclock_receive(peer); 1408 } 1409 } 1410 if (dtemp > 0) 1411 record_clock_stats(&peer->srcadr, pp->a_lastcode); 1412 #ifdef DEBUG 1413 if (debug) 1414 printf("chu: timecode %d %s\n", pp->lencode, 1415 pp->a_lastcode); 1416 #endif 1417 #ifdef ICOM 1418 chu_newchan(peer, dtemp); 1419 #endif /* ICOM */ 1420 chu_clear(peer); 1421 if (up->errflg) 1422 refclock_report(peer, up->errflg); 1423 up->errflg = 0; 1424 } 1425 1426 1427 /* 1428 * chu_major - majority decoder 1429 */ 1430 static double 1431 chu_major( 1432 struct peer *peer /* peer structure pointer */ 1433 ) 1434 { 1435 struct refclockproc *pp; 1436 struct chuunit *up; 1437 1438 u_char code[11]; /* decoded timecode */ 1439 int metric; /* distance metric */ 1440 int val1; /* maximum distance */ 1441 int synchar; /* stray cat */ 1442 int temp; 1443 int i, j, k; 1444 1445 pp = peer->procptr; 1446 up = (struct chuunit *)pp->unitptr; 1447 1448 /* 1449 * Majority decoder. Each burst encodes two replications at each 1450 * digit position in the timecode. Each row of the decoding 1451 * matrix encodes the number of occurences of each digit found 1452 * at the corresponding position. The maximum over all 1453 * occurrences at each position is the distance for this 1454 * position and the corresponding digit is the maximum- 1455 * likelihood candidate. If the distance is not more than half 1456 * the total number of occurences, a majority has not been found 1457 * and the data are discarded. The decoding distance is defined 1458 * as the sum of the distances over the first nine digits. The 1459 * tenth digit varies over the seconds, so we don't count it. 1460 */ 1461 metric = 0; 1462 for (i = 0; i < 9; i++) { 1463 val1 = 0; 1464 k = 0; 1465 for (j = 0; j < 16; j++) { 1466 temp = up->decode[i][j] + up->decode[i + 10][j]; 1467 if (temp > val1) { 1468 val1 = temp; 1469 k = j; 1470 } 1471 } 1472 if (val1 <= up->burstcnt) 1473 up->status |= DECODE; 1474 metric += val1; 1475 code[i] = hexchar[k]; 1476 } 1477 1478 /* 1479 * Compute the timecode timestamp from the days, hours and 1480 * minutes of the timecode. Use clocktime() for the aggregate 1481 * minutes and the minute offset computed from the burst 1482 * seconds. Note that this code relies on the filesystem time 1483 * for the years and does not use the years of the timecode. 1484 */ 1485 if (sscanf((char *)code, "%1x%3d%2d%2d", &synchar, &pp->day, 1486 &pp->hour, &pp->minute) != 4) 1487 up->status |= DECODE; 1488 if (up->ntstamp < MINSTAMP) 1489 up->status |= STAMP; 1490 return (metric); 1491 } 1492 1493 1494 /* 1495 * chu_clear - clear decoding matrix 1496 */ 1497 static void 1498 chu_clear( 1499 struct peer *peer /* peer structure pointer */ 1500 ) 1501 { 1502 struct refclockproc *pp; 1503 struct chuunit *up; 1504 int i, j; 1505 1506 pp = peer->procptr; 1507 up = (struct chuunit *)pp->unitptr; 1508 1509 /* 1510 * Clear stuff for the minute. 1511 */ 1512 up->ndx = up->prevsec = 0; 1513 up->burstcnt = up->ntstamp = 0; 1514 up->status &= INSYNC | METRIC; 1515 for (i = 0; i < 20; i++) { 1516 for (j = 0; j < 16; j++) 1517 up->decode[i][j] = 0; 1518 } 1519 } 1520 1521 #ifdef ICOM 1522 /* 1523 * chu_newchan - called once per minute to find the best channel; 1524 * returns zero on success, nonzero if ICOM error. 1525 */ 1526 static int 1527 chu_newchan( 1528 struct peer *peer, 1529 double met 1530 ) 1531 { 1532 struct chuunit *up; 1533 struct refclockproc *pp; 1534 struct xmtr *sp; 1535 int rval; 1536 double metric; 1537 int i; 1538 1539 pp = peer->procptr; 1540 up = (struct chuunit *)pp->unitptr; 1541 1542 /* 1543 * The radio can be tuned to three channels: 0 (3330 kHz), 1 1544 * (7850 kHz) and 2 (14670 kHz). There are five one-minute 1545 * dwells in each cycle. During the first dwell the radio is 1546 * tuned to one of the three channels to measure the channel 1547 * metric. The channel is selected as the one least recently 1548 * measured. During the remaining four dwells the radio is tuned 1549 * to the channel with the highest channel metric. 1550 */ 1551 if (up->fd_icom <= 0) 1552 return (0); 1553 1554 /* 1555 * Update the current channel metric and age of all channels. 1556 * Scan all channels for the highest metric. 1557 */ 1558 sp = &up->xmtr[up->chan]; 1559 sp->metric -= sp->integ[sp->iptr]; 1560 sp->integ[sp->iptr] = met; 1561 sp->metric += sp->integ[sp->iptr]; 1562 sp->probe = 0; 1563 sp->iptr = (sp->iptr + 1) % ISTAGE; 1564 metric = 0; 1565 for (i = 0; i < NCHAN; i++) { 1566 up->xmtr[i].probe++; 1567 if (up->xmtr[i].metric > metric) { 1568 up->status |= METRIC; 1569 metric = up->xmtr[i].metric; 1570 up->chan = i; 1571 } 1572 } 1573 1574 /* 1575 * Start the next dwell. If the first dwell or no stations have 1576 * been heard, continue round-robin scan. 1577 */ 1578 up->dwell = (up->dwell + 1) % DWELL; 1579 if (up->dwell == 0 || metric == 0) { 1580 rval = 0; 1581 for (i = 0; i < NCHAN; i++) { 1582 if (up->xmtr[i].probe > rval) { 1583 rval = up->xmtr[i].probe; 1584 up->chan = i; 1585 } 1586 } 1587 } 1588 1589 /* Retune the radio at each dwell in case somebody nudges the 1590 * tuning knob. 1591 */ 1592 rval = icom_freq(up->fd_icom, peer->ttl & 0x7f, qsy[up->chan] + 1593 TUNE); 1594 snprintf(up->ident, sizeof(up->ident), "CHU%d", up->chan); 1595 memcpy(&pp->refid, up->ident, 4); 1596 memcpy(&peer->refid, up->ident, 4); 1597 if (metric == 0 && up->status & METRIC) { 1598 up->status &= ~METRIC; 1599 refclock_report(peer, CEVNT_PROP); 1600 } 1601 return (rval); 1602 } 1603 #endif /* ICOM */ 1604 1605 1606 /* 1607 * chu_dist - determine the distance of two octet arguments 1608 */ 1609 static int 1610 chu_dist( 1611 int x, /* an octet of bits */ 1612 int y /* another octet of bits */ 1613 ) 1614 { 1615 int val; /* bit count */ 1616 int temp; 1617 int i; 1618 1619 /* 1620 * The distance is determined as the weight of the exclusive OR 1621 * of the two arguments. The weight is determined by the number 1622 * of one bits in the result. Each one bit increases the weight, 1623 * while each zero bit decreases it. 1624 */ 1625 temp = x ^ y; 1626 val = 0; 1627 for (i = 0; i < 8; i++) { 1628 if ((temp & 0x1) == 0) 1629 val++; 1630 else 1631 val--; 1632 temp >>= 1; 1633 } 1634 return (val); 1635 } 1636 1637 1638 #ifdef HAVE_AUDIO 1639 /* 1640 * chu_gain - adjust codec gain 1641 * 1642 * This routine is called at the end of each second. During the second 1643 * the number of signal clips above the MAXAMP threshold (6000). If 1644 * there are no clips, the gain is bumped up; if there are more than 1645 * MAXCLP clips (100), it is bumped down. The decoder is relatively 1646 * insensitive to amplitude, so this crudity works just peachy. The 1647 * routine also jiggles the input port and selectively mutes the 1648 */ 1649 static void 1650 chu_gain( 1651 struct peer *peer /* peer structure pointer */ 1652 ) 1653 { 1654 struct refclockproc *pp; 1655 struct chuunit *up; 1656 1657 pp = peer->procptr; 1658 up = (struct chuunit *)pp->unitptr; 1659 1660 /* 1661 * Apparently, the codec uses only the high order bits of the 1662 * gain control field. Thus, it may take awhile for changes to 1663 * wiggle the hardware bits. 1664 */ 1665 if (up->clipcnt == 0) { 1666 up->gain += 4; 1667 if (up->gain > MAXGAIN) 1668 up->gain = MAXGAIN; 1669 } else if (up->clipcnt > MAXCLP) { 1670 up->gain -= 4; 1671 if (up->gain < 0) 1672 up->gain = 0; 1673 } 1674 audio_gain(up->gain, up->mongain, up->port); 1675 up->clipcnt = 0; 1676 } 1677 #endif /* HAVE_AUDIO */ 1678 1679 1680 #else 1681 int refclock_chu_bs; 1682 #endif /* REFCLOCK */ 1683