/contrib/ntp/ntpd/refclock_chu.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 1687 lines · 1044 code · 124 blank · 519 comment · 187 complexity · 80c4a4fc3e837b9804bf43bab4d88afd MD5 · raw file

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