Coverage Report

Created: 2023-05-19 06:16

/src/ntp-dev/ntpd/refclock_chu.c
Line
Count
Source (jump to first uncovered line)
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
8
#include "ntp_types.h"
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
0
#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
0
#define SPEED232  B300  /* UART speed (300 baud) */
214
#ifdef ICOM
215
0
#define TUNE    .001  /* offset for narrow filter (MHz) */
216
0
#define DWELL   5  /* minutes in a dwell */
217
0
#define NCHAN   3  /* number of channels */
218
0
#define ISTAGE    3  /* number of integrator stages */
219
#endif /* ICOM */
220
221
#ifdef HAVE_AUDIO
222
/*
223
 * Audio demodulator definitions
224
 */
225
0
#define SECOND    8000  /* nominal sample rate (Hz) */
226
0
#define BAUD    300  /* modulation rate (bps) */
227
0
#define OFFSET    128  /* companded sample offset */
228
#define SIZE    256 /* decompanding table size */
229
0
#define MAXAMP    6000.  /* maximum signal level */
230
0
#define MAXCLP    100  /* max clips above reference per s */
231
0
#define SPAN    800.  /* min envelope span */
232
0
#define LIMIT   1000.  /* soft limiter threshold */
233
0
#define AGAIN   6.  /* baseband gain */
234
0
#define LAG   10  /* discriminator lag */
235
0
#define DEVICE_AUDIO  "/dev/audio" /* device name */
236
0
#define DESCRIPTION "CHU Audio/Modem Receiver" /* WRU */
237
0
#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
0
#define CHAR    (11. / 300.) /* character time (s) */
246
0
#define BURST   11  /* max characters per burst */
247
0
#define MINCHARS    9  /* min characters per burst */
248
0
#define MINDIST   28  /* min burst distance (of 40)  */
249
0
#define MINSYNC   8  /* min sync distance (of 16) */
250
0
#define MINSTAMP  20  /* min timestamps (of 60) */
251
0
#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
0
#define PDELAY  ((170 + .8 + 4.7 + 1.3) / 1000)  /* system delay (s) */
268
269
/*
270
 * Status bits (status)
271
 */
272
0
#define RUNT    0x0001  /* runt burst */
273
0
#define NOISE   0x0002  /* noise burst */
274
0
#define BFRAME    0x0004  /* invalid format B frame sync */
275
0
#define BFORMAT   0x0008  /* invalid format B data */
276
0
#define AFRAME    0x0010  /* invalid format A frame sync */
277
0
#define AFORMAT   0x0020  /* invalid format A data */
278
0
#define DECODE    0x0040  /* invalid data decode */
279
0
#define STAMP   0x0080  /* too few timestamps */
280
0
#define AVALID    0x0100  /* valid A frame */
281
0
#define BVALID    0x0200  /* valid B frame */
282
0
#define INSYNC    0x0400  /* clock synchronized */
283
0
#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
0
#define SYNERR    0x01  /* frame sync error */
295
0
#define FMTERR    0x02  /* data format error */
296
0
#define DECERR    0x04  /* data decoding error */
297
0
#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
0
{
467
0
  struct chuunit *up;
468
0
  struct refclockproc *pp;
469
0
  char device[20];  /* device name */
470
0
  int fd;   /* file descriptor */
471
0
#ifdef ICOM
472
0
  int temp;
473
0
#endif /* ICOM */
474
0
#ifdef HAVE_AUDIO
475
0
  int fd_audio; /* audio port file descriptor */
476
0
  int i;    /* index */
477
0
  double  step;   /* codec adjustment */
478
479
  /*
480
   * Open audio device. Don't complain if not there.
481
   */
482
0
  fd_audio = audio_init(DEVICE_AUDIO, AUDIO_BUFSIZ, unit);
483
484
0
#ifdef DEBUG
485
0
  if (fd_audio >= 0 && debug)
486
0
    audio_show();
487
0
#endif
488
489
  /*
490
   * If audio is unavailable, Open serial port in raw mode.
491
   */
492
0
  if (fd_audio >= 0) {
493
0
    fd = fd_audio;
494
0
  } else {
495
0
    snprintf(device, sizeof(device), DEVICE, unit);
496
0
    fd = refclock_open(device, SPEED232, LDISC_RAW);
497
0
  }
498
#else /* HAVE_AUDIO */
499
500
  /*
501
   * Open serial port in raw mode.
502
   */
503
  snprintf(device, sizeof(device), DEVICE, unit);
504
  fd = refclock_open(device, SPEED232, LDISC_RAW);
505
#endif /* HAVE_AUDIO */
506
507
0
  if (fd < 0)
508
0
    return (0);
509
510
  /*
511
   * Allocate and initialize unit structure
512
   */
513
0
  up = emalloc_zero(sizeof(*up));
514
0
  pp = peer->procptr;
515
0
  pp->unitptr = up;
516
0
  pp->io.clock_recv = chu_receive;
517
0
  pp->io.srcclock = peer;
518
0
  pp->io.datalen = 0;
519
0
  pp->io.fd = fd;
520
0
  if (!io_addclock(&pp->io)) {
521
0
    close(fd);
522
0
    pp->io.fd = -1;
523
0
    free(up);
524
0
    pp->unitptr = NULL;
525
0
    return (0);
526
0
  }
527
528
  /*
529
   * Initialize miscellaneous variables
530
   */
531
0
  peer->precision = PRECISION;
532
0
  pp->clockdesc = DESCRIPTION;
533
0
  strlcpy(up->ident, "CHU", sizeof(up->ident));
534
0
  memcpy(&pp->refid, up->ident, 4); 
535
0
  DTOLFP(CHAR, &up->charstamp);
536
0
#ifdef HAVE_AUDIO
537
538
  /*
539
   * The companded samples are encoded sign-magnitude. The table
540
   * contains all the 256 values in the interest of speed. We do
541
   * this even if the audio codec is not available. C'est la lazy.
542
   */
543
0
  up->fd_audio = fd_audio;
544
0
  up->gain = 127;
545
0
  up->comp[0] = up->comp[OFFSET] = 0.;
546
0
  up->comp[1] = 1; up->comp[OFFSET + 1] = -1.;
547
0
  up->comp[2] = 3; up->comp[OFFSET + 2] = -3.;
548
0
  step = 2.;
549
0
  for (i = 3; i < OFFSET; i++) {
550
0
    up->comp[i] = up->comp[i - 1] + step;
551
0
    up->comp[OFFSET + i] = -up->comp[i];
552
0
                if (i % 16 == 0)
553
0
                  step *= 2.;
554
0
  }
555
0
  DTOLFP(1. / SECOND, &up->tick);
556
0
#endif /* HAVE_AUDIO */
557
0
#ifdef ICOM
558
0
  temp = 0;
559
0
#ifdef DEBUG
560
0
  if (debug > 1)
561
0
    temp = P_TRACE;
562
0
#endif
563
0
  if (peer->ttl > 0) {
564
0
    if (peer->ttl & 0x80)
565
0
      up->fd_icom = icom_init("/dev/icom", B1200,
566
0
          temp);
567
0
    else
568
0
      up->fd_icom = icom_init("/dev/icom", B9600,
569
0
          temp);
570
0
  }
571
0
  if (up->fd_icom > 0) {
572
0
    if (chu_newchan(peer, 0) != 0) {
573
0
      msyslog(LOG_NOTICE, "icom: radio not found");
574
0
      close(up->fd_icom);
575
0
      up->fd_icom = 0;
576
0
    } else {
577
0
      msyslog(LOG_NOTICE, "icom: autotune enabled");
578
0
    }
579
0
  }
580
0
#endif /* ICOM */
581
0
  return (1);
582
0
}
583
584
585
/*
586
 * chu_shutdown - shut down the clock
587
 */
588
static void
589
chu_shutdown(
590
  int unit,   /* instance number (not used) */
591
  struct peer *peer /* peer structure pointer */
592
  )
593
0
{
594
0
  struct chuunit *up;
595
0
  struct refclockproc *pp;
596
597
0
  pp = peer->procptr;
598
0
  up = pp->unitptr;
599
0
  if (up == NULL)
600
0
    return;
601
602
0
  io_closeclock(&pp->io);
603
0
#ifdef ICOM
604
0
  if (up->fd_icom > 0)
605
0
    close(up->fd_icom);
606
0
#endif /* ICOM */
607
0
  free(up);
608
0
}
609
610
611
/*
612
 * chu_receive - receive data from the audio or serial device
613
 */
614
static void
615
chu_receive(
616
  struct recvbuf *rbufp /* receive buffer structure pointer */
617
  )
618
0
{
619
0
#ifdef HAVE_AUDIO
620
0
  struct chuunit *up;
621
0
  struct refclockproc *pp;
622
0
  struct peer *peer;
623
624
0
  peer = rbufp->recv_peer;
625
0
  pp = peer->procptr;
626
0
  up = pp->unitptr;
627
628
  /*
629
   * If the audio codec is warmed up, the buffer contains codec
630
   * samples which need to be demodulated and decoded into CHU
631
   * characters using the software UART. Otherwise, the buffer
632
   * contains CHU characters from the serial port, so the software
633
   * UART is bypassed. In this case the CPU will probably run a
634
   * few degrees cooler.
635
   */
636
0
  if (up->fd_audio > 0)
637
0
    chu_audio_receive(rbufp);
638
0
  else
639
0
    chu_serial_receive(rbufp);
640
#else
641
  chu_serial_receive(rbufp);
642
#endif /* HAVE_AUDIO */
643
0
}
644
645
646
#ifdef HAVE_AUDIO
647
/*
648
 * chu_audio_receive - receive data from the audio device
649
 */
650
static void
651
chu_audio_receive(
652
  struct recvbuf *rbufp /* receive buffer structure pointer */
653
  )
654
0
{
655
0
  struct chuunit *up;
656
0
  struct refclockproc *pp;
657
0
  struct peer *peer;
658
659
0
  double  sample;   /* codec sample */
660
0
  u_char  *dpt;   /* buffer pointer */
661
0
  int bufcnt;   /* buffer counter */
662
0
  l_fp  ltemp;    /* l_fp temp */
663
664
0
  peer = rbufp->recv_peer;
665
0
  pp = peer->procptr;
666
0
  up = pp->unitptr;
667
668
  /*
669
   * Main loop - read until there ain't no more. Note codec
670
   * samples are bit-inverted.
671
   */
672
0
  DTOLFP((double)rbufp->recv_length / SECOND, &ltemp);
673
0
  L_SUB(&rbufp->recv_time, &ltemp);
674
0
  up->timestamp = rbufp->recv_time;
675
0
  dpt = rbufp->recv_buffer;
676
0
  for (bufcnt = 0; bufcnt < rbufp->recv_length; bufcnt++) {
677
0
    sample = up->comp[~*dpt++ & 0xff];
678
679
    /*
680
     * Clip noise spikes greater than MAXAMP. If no clips,
681
     * increase the gain a tad; if the clips are too high, 
682
     * decrease a tad.
683
     */
684
0
    if (sample > MAXAMP) {
685
0
      sample = MAXAMP;
686
0
      up->clipcnt++;
687
0
    } else if (sample < -MAXAMP) {
688
0
      sample = -MAXAMP;
689
0
      up->clipcnt++;
690
0
    }
691
0
    chu_rf(peer, sample);
692
0
    L_ADD(&up->timestamp, &up->tick);
693
694
    /*
695
     * Once each second ride gain.
696
     */
697
0
    up->seccnt = (up->seccnt + 1) % SECOND;
698
0
    if (up->seccnt == 0) {
699
0
      chu_gain(peer);
700
0
    }
701
0
  }
702
703
  /*
704
   * Set the input port and monitor gain for the next buffer.
705
   */
706
0
  if (pp->sloppyclockflag & CLK_FLAG2)
707
0
    up->port = 2;
708
0
  else
709
0
    up->port = 1;
710
0
  if (pp->sloppyclockflag & CLK_FLAG3)
711
0
    up->mongain = MONGAIN;
712
0
  else
713
0
    up->mongain = 0;
714
0
}
715
716
717
/*
718
 * chu_rf - filter and demodulate the FSK signal
719
 *
720
 * This routine implements a 300-baud Bell 103 modem with mark 2225 Hz
721
 * and space 2025 Hz. It uses a bandpass filter followed by a soft
722
 * limiter, FM discriminator and lowpass filter. A maximum-likelihood
723
 * decoder samples the baseband signal at eight times the baud rate and
724
 * detects the start bit of each character.
725
 *
726
 * The filters are built for speed, which explains the rather clumsy
727
 * code. Hopefully, the compiler will efficiently implement the move-
728
 * and-muiltiply-and-add operations.
729
 */
730
static void
731
chu_rf(
732
  struct peer *peer,  /* peer structure pointer */
733
  double  sample    /* analog sample */
734
  )
735
0
{
736
0
  struct refclockproc *pp;
737
0
  struct chuunit *up;
738
0
  struct surv *sp;
739
740
  /*
741
   * Local variables
742
   */
743
0
  double  signal;   /* bandpass signal */
744
0
  double  limit;    /* limiter signal */
745
0
  double  disc;   /* discriminator signal */
746
0
  double  lpf;    /* lowpass signal */
747
0
  double  dist;   /* UART signal distance */
748
0
  int i, j;
749
750
0
  pp = peer->procptr;
751
0
  up = pp->unitptr;
752
753
  /*
754
   * Bandpass filter. 4th-order elliptic, 500-Hz bandpass centered
755
   * at 2125 Hz. Passband ripple 0.3 dB, stopband ripple 50 dB,
756
   * phase delay 0.24 ms.
757
   */
758
0
  signal = (up->bpf[8] = up->bpf[7]) * 5.844676e-01;
759
0
  signal += (up->bpf[7] = up->bpf[6]) * 4.884860e-01;
760
0
  signal += (up->bpf[6] = up->bpf[5]) * 2.704384e+00;
761
0
  signal += (up->bpf[5] = up->bpf[4]) * 1.645032e+00;
762
0
  signal += (up->bpf[4] = up->bpf[3]) * 4.644557e+00;
763
0
  signal += (up->bpf[3] = up->bpf[2]) * 1.879165e+00;
764
0
  signal += (up->bpf[2] = up->bpf[1]) * 3.522634e+00;
765
0
  signal += (up->bpf[1] = up->bpf[0]) * 7.315738e-01;
766
0
  up->bpf[0] = sample - signal;
767
0
  signal = up->bpf[0] * 6.176213e-03
768
0
      + up->bpf[1] * 3.156599e-03
769
0
      + up->bpf[2] * 7.567487e-03
770
0
      + up->bpf[3] * 4.344580e-03
771
0
      + up->bpf[4] * 1.190128e-02
772
0
      + up->bpf[5] * 4.344580e-03
773
0
      + up->bpf[6] * 7.567487e-03
774
0
      + up->bpf[7] * 3.156599e-03
775
0
      + up->bpf[8] * 6.176213e-03;
776
777
0
  up->monitor = signal / 4.;  /* note monitor after filter */
778
779
  /*
780
   * Soft limiter/discriminator. The 11-sample discriminator lag
781
   * interval corresponds to three cycles of 2125 Hz, which
782
   * requires the sample frequency to be 2125 * 11 / 3 = 7791.7
783
   * Hz. The discriminator output varies +-0.5 interval for input
784
   * frequency 2025-2225 Hz. However, we don't get to sample at
785
   * this frequency, so the discriminator output is biased. Life
786
   * at 8000 Hz sucks.
787
   */
788
0
  limit = signal;
789
0
  if (limit > LIMIT)
790
0
    limit = LIMIT;
791
0
  else if (limit < -LIMIT)
792
0
    limit = -LIMIT;
793
0
  disc = up->disc[up->discptr] * -limit;
794
0
  up->disc[up->discptr] = limit;
795
0
  up->discptr = (up->discptr + 1 ) % LAG;
796
0
  if (disc >= 0)
797
0
    disc = SQRT(disc);
798
0
  else
799
0
    disc = -SQRT(-disc);
800
801
  /*
802
   * Lowpass filter. Raised cosine FIR, Ts = 1 / 300, beta = 0.1.
803
   */
804
0
  lpf = (up->lpf[26] = up->lpf[25]) * 2.538771e-02;
805
0
  lpf += (up->lpf[25] = up->lpf[24]) * 1.084671e-01;
806
0
  lpf += (up->lpf[24] = up->lpf[23]) * 2.003159e-01;
807
0
  lpf += (up->lpf[23] = up->lpf[22]) * 2.985303e-01;
808
0
  lpf += (up->lpf[22] = up->lpf[21]) * 4.003697e-01;
809
0
  lpf += (up->lpf[21] = up->lpf[20]) * 5.028552e-01;
810
0
  lpf += (up->lpf[20] = up->lpf[19]) * 6.028795e-01;
811
0
  lpf += (up->lpf[19] = up->lpf[18]) * 6.973249e-01;
812
0
  lpf += (up->lpf[18] = up->lpf[17]) * 7.831828e-01;
813
0
  lpf += (up->lpf[17] = up->lpf[16]) * 8.576717e-01;
814
0
  lpf += (up->lpf[16] = up->lpf[15]) * 9.183463e-01;
815
0
  lpf += (up->lpf[15] = up->lpf[14]) * 9.631951e-01;
816
0
  lpf += (up->lpf[14] = up->lpf[13]) * 9.907208e-01;
817
0
  lpf += (up->lpf[13] = up->lpf[12]) * 1.000000e+00;
818
0
  lpf += (up->lpf[12] = up->lpf[11]) * 9.907208e-01;
819
0
  lpf += (up->lpf[11] = up->lpf[10]) * 9.631951e-01;
820
0
  lpf += (up->lpf[10] = up->lpf[9]) * 9.183463e-01;
821
0
  lpf += (up->lpf[9] = up->lpf[8]) * 8.576717e-01;
822
0
  lpf += (up->lpf[8] = up->lpf[7]) * 7.831828e-01;
823
0
  lpf += (up->lpf[7] = up->lpf[6]) * 6.973249e-01;
824
0
  lpf += (up->lpf[6] = up->lpf[5]) * 6.028795e-01;
825
0
  lpf += (up->lpf[5] = up->lpf[4]) * 5.028552e-01;
826
0
  lpf += (up->lpf[4] = up->lpf[3]) * 4.003697e-01;
827
0
  lpf += (up->lpf[3] = up->lpf[2]) * 2.985303e-01;
828
0
  lpf += (up->lpf[2] = up->lpf[1]) * 2.003159e-01;
829
0
  lpf += (up->lpf[1] = up->lpf[0]) * 1.084671e-01;
830
0
  lpf += up->lpf[0] = disc * 2.538771e-02;
831
832
  /*
833
   * Maximum-likelihood decoder. The UART updates each of the
834
   * eight survivors and determines the span, slice level and
835
   * tentative decoded character. Valid 11-bit characters are
836
   * framed so that bit 10 and bit 11 (stop bits) are mark and bit
837
   * 1 (start bit) is space. When a valid character is found, the
838
   * survivor with maximum distance determines the final decoded
839
   * character.
840
   */
841
0
  up->baud += 1. / SECOND;
842
0
  if (up->baud > 1. / (BAUD * 8.)) {
843
0
    up->baud -= 1. / (BAUD * 8.);
844
0
    up->decptr = (up->decptr + 1) % 8;
845
0
    sp = &up->surv[up->decptr];
846
0
    sp->cstamp = up->timestamp;
847
0
    chu_uart(sp, -lpf * AGAIN);
848
0
    if (up->dbrk > 0) {
849
0
      up->dbrk--;
850
0
      if (up->dbrk > 0)
851
0
        return;
852
853
0
      up->decpha = up->decptr;
854
0
    }
855
0
    if (up->decptr != up->decpha)
856
0
      return;
857
858
0
    dist = 0;
859
0
    j = -1;
860
0
    for (i = 0; i < 8; i++) {
861
862
      /*
863
       * The timestamp is taken at the last bit, so
864
       * for correct decoding we reqire sufficient
865
       * span and correct start bit and two stop bits.
866
       */
867
0
      if ((up->surv[i].uart & 0x601) != 0x600 ||
868
0
          up->surv[i].span < SPAN)
869
0
        continue;
870
871
0
      if (up->surv[i].dist > dist) {
872
0
        dist = up->surv[i].dist;
873
0
        j = i;
874
0
      }
875
0
    }
876
0
    if (j < 0)
877
0
      return;
878
879
    /*
880
     * Process the character, then blank the decoder until
881
     * the end of the next character.This sets the decoding
882
     * phase of the entire burst from the phase of the first
883
     * character.
884
     */
885
0
    up->maxsignal = up->surv[j].span;
886
0
    chu_decode(peer, (up->surv[j].uart >> 1) & 0xff,
887
0
        up->surv[j].cstamp);
888
0
    up->dbrk = 88;
889
0
  }
890
0
}
891
892
893
/*
894
 * chu_uart - maximum-likelihood UART
895
 *
896
 * This routine updates a shift register holding the last 11 envelope
897
 * samples. It then computes the slice level and span over these samples
898
 * and determines the tentative data bits and distance. The calling
899
 * program selects over the last eight survivors the one with maximum
900
 * distance to determine the decoded character.
901
 */
902
static void
903
chu_uart(
904
  struct surv *sp,  /* survivor structure pointer */
905
  double  sample    /* baseband signal */
906
  )
907
0
{
908
0
  double  es_max, es_min; /* max/min envelope */
909
0
  double  slice;    /* slice level */
910
0
  double  dist;   /* distance */
911
0
  double  dtemp;
912
0
  int i;
913
914
  /*
915
   * Save the sample and shift right. At the same time, measure
916
   * the maximum and minimum over all eleven samples.
917
   */
918
0
  es_max = -1e6;
919
0
  es_min = 1e6;
920
0
  sp->shift[0] = sample;
921
0
  for (i = 11; i > 0; i--) {
922
0
    sp->shift[i] = sp->shift[i - 1];
923
0
    if (sp->shift[i] > es_max)
924
0
      es_max = sp->shift[i];
925
0
    if (sp->shift[i] < es_min)
926
0
      es_min = sp->shift[i];
927
0
  }
928
929
  /*
930
   * Determine the span as the maximum less the minimum and the
931
   * slice level as the minimum plus a fraction of the span. Note
932
   * the slight bias toward mark to correct for the modem tendency
933
   * to make more mark than space errors. Compute the distance on
934
   * the assumption the last two bits must be mark, the first
935
   * space and the rest either mark or space. 
936
   */ 
937
0
  sp->span = es_max - es_min;
938
0
  slice = es_min + .45 * sp->span;
939
0
  dist = 0;
940
0
  sp->uart = 0;
941
0
  for (i = 1; i < 12; i++) {
942
0
    sp->uart <<= 1;
943
0
    dtemp = sp->shift[i];
944
0
    if (dtemp > slice)
945
0
      sp->uart |= 0x1;
946
0
    if (i == 1 || i == 2) {
947
0
      dist += dtemp - es_min;
948
0
    } else if (i == 11) {
949
0
      dist += es_max - dtemp;
950
0
    } else {
951
0
      if (dtemp > slice)
952
0
        dist += dtemp - es_min;
953
0
      else
954
0
        dist += es_max - dtemp;
955
0
    }
956
0
  }
957
0
  sp->dist = dist / (11 * sp->span);
958
0
}
959
#endif /* HAVE_AUDIO */
960
961
962
/*
963
 * chu_serial_receive - receive data from the serial device
964
 */
965
static void
966
chu_serial_receive(
967
  struct recvbuf *rbufp /* receive buffer structure pointer */
968
  )
969
0
{
970
0
  struct peer *peer;
971
972
0
  u_char  *dpt;   /* receive buffer pointer */
973
974
0
  peer = rbufp->recv_peer;
975
976
0
  dpt = (u_char *)&rbufp->recv_space;
977
0
  chu_decode(peer, *dpt, rbufp->recv_time);
978
0
}
979
980
981
/*
982
 * chu_decode - decode the character data
983
 */
984
static void
985
chu_decode(
986
  struct peer *peer,  /* peer structure pointer */
987
  int hexhex,   /* data character */
988
  l_fp  cstamp    /* data character timestamp */
989
  )
990
0
{
991
0
  struct refclockproc *pp;
992
0
  struct chuunit *up;
993
994
0
  l_fp  tstmp;    /* timestamp temp */
995
0
  double  dtemp;
996
997
0
  pp = peer->procptr;
998
0
  up = pp->unitptr;
999
1000
  /*
1001
   * If the interval since the last character is greater than the
1002
   * longest burst, process the last burst and start a new one. If
1003
   * the interval is less than this but greater than two
1004
   * characters, consider this a noise burst and reject it.
1005
   */
1006
0
  tstmp = up->timestamp;
1007
0
  if (L_ISZERO(&up->laststamp))
1008
0
    up->laststamp = up->timestamp;
1009
0
  L_SUB(&tstmp, &up->laststamp);
1010
0
  up->laststamp = up->timestamp;
1011
0
  LFPTOD(&tstmp, dtemp);
1012
0
  if (dtemp > BURST * CHAR) {
1013
0
    chu_burst(peer);
1014
0
    up->ndx = 0;
1015
0
  } else if (dtemp > 2.5 * CHAR) {
1016
0
    up->ndx = 0;
1017
0
  }
1018
1019
  /*
1020
   * Append the character to the current burst and append the
1021
   * character timestamp to the timestamp list.
1022
   */
1023
0
  if (up->ndx < BURST) {
1024
0
    up->cbuf[up->ndx] = hexhex & 0xff;
1025
0
    up->cstamp[up->ndx] = cstamp;
1026
0
    up->ndx++;
1027
1028
0
  }
1029
0
}
1030
1031
1032
/*
1033
 * chu_burst - search for valid burst format
1034
 */
1035
static void
1036
chu_burst(
1037
  struct peer *peer
1038
  )
1039
0
{
1040
0
  struct chuunit *up;
1041
0
  struct refclockproc *pp;
1042
1043
0
  int i;
1044
1045
0
  pp = peer->procptr;
1046
0
  up = pp->unitptr;
1047
1048
  /*
1049
   * Correlate a block of five characters with the next block of
1050
   * five characters. The burst distance is defined as the number
1051
   * of bits that match in the two blocks for format A and that
1052
   * match the inverse for format B.
1053
   */
1054
0
  if (up->ndx < MINCHARS) {
1055
0
    up->status |= RUNT;
1056
0
    return;
1057
0
  }
1058
0
  up->burdist = 0;
1059
0
  for (i = 0; i < 5 && i < up->ndx - 5; i++)
1060
0
    up->burdist += chu_dist(up->cbuf[i], up->cbuf[i + 5]);
1061
1062
  /*
1063
   * If the burst distance is at least MINDIST, this must be a
1064
   * format A burst; if the value is not greater than -MINDIST, it
1065
   * must be a format B burst. If the B burst is perfect, we
1066
   * believe it; otherwise, it is a noise burst and of no use to
1067
   * anybody.
1068
   */
1069
0
  if (up->burdist >= MINDIST) {
1070
0
    chu_a(peer, up->ndx);
1071
0
  } else if (up->burdist <= -MINDIST) {
1072
0
    chu_b(peer, up->ndx);
1073
0
  } else {
1074
0
    up->status |= NOISE;
1075
0
    return;
1076
0
  }
1077
1078
  /*
1079
   * If this is a valid burst, wait a guard time of ten seconds to
1080
   * allow for more bursts, then arm the poll update routine to
1081
   * process the minute. Don't do this if this is called from the
1082
   * timer interrupt routine.
1083
   */
1084
0
  if (peer->outdate != current_time)
1085
0
    peer->nextdate = current_time + 10;
1086
0
}
1087
1088
1089
/*
1090
 * chu_b - decode format B burst
1091
 */
1092
static void
1093
chu_b(
1094
  struct peer *peer,
1095
  int nchar
1096
  )
1097
0
{
1098
0
  struct  refclockproc *pp;
1099
0
  struct  chuunit *up;
1100
1101
0
  u_char  code[11]; /* decoded timecode */
1102
0
  char  tbuf[80]; /* trace buffer */
1103
0
  char *  p;
1104
0
  size_t  chars;
1105
0
  size_t  cb;
1106
0
  int i;
1107
1108
0
  pp = peer->procptr;
1109
0
  up = pp->unitptr;
1110
1111
  /*
1112
   * In a format B burst, a character is considered valid only if
1113
   * the first occurence matches the last occurence. The burst is
1114
   * considered valid only if all characters are valid; that is,
1115
   * only if the distance is 40. Note that once a valid frame has
1116
   * been found errors are ignored.
1117
   */
1118
0
  snprintf(tbuf, sizeof(tbuf), "chuB %04x %4.0f %2d %2d ",
1119
0
     up->status, up->maxsignal, nchar, -up->burdist);
1120
0
  cb = sizeof(tbuf);
1121
0
  p = tbuf;
1122
0
  for (i = 0; i < nchar; i++) {
1123
0
    chars = strlen(p);
1124
0
    if (cb < chars + 1) {
1125
0
      msyslog(LOG_ERR, "chu_b() fatal out buffer");
1126
0
      exit(1);
1127
0
    }
1128
0
    cb -= chars;
1129
0
    p += chars;
1130
0
    snprintf(p, cb, "%02x", up->cbuf[i]);
1131
0
  }
1132
0
  if (pp->sloppyclockflag & CLK_FLAG4)
1133
0
    record_clock_stats(&peer->srcadr, tbuf);
1134
0
#ifdef DEBUG
1135
0
  if (debug)
1136
0
    printf("%s\n", tbuf);
1137
0
#endif
1138
0
  if (up->burdist > -40) {
1139
0
    up->status |= BFRAME;
1140
0
    return;
1141
0
  }
1142
1143
  /*
1144
   * Convert the burst data to internal format. Don't bother with
1145
   * the timestamps.
1146
   */
1147
0
  for (i = 0; i < 5; i++) {
1148
0
    code[2 * i] = hexchar[up->cbuf[i] & 0xf];
1149
0
    code[2 * i + 1] = hexchar[(up->cbuf[i] >>
1150
0
        4) & 0xf];
1151
0
  }
1152
0
  if (sscanf((char *)code, "%1x%1d%4d%2d%2x", &up->leap, &up->dut,
1153
0
      &pp->year, &up->tai, &up->dst) != 5) {
1154
0
    up->status |= BFORMAT;
1155
0
    return;
1156
0
  }
1157
0
  up->status |= BVALID;
1158
0
  if (up->leap & 0x8)
1159
0
    up->dut = -up->dut;
1160
0
}
1161
1162
1163
/*
1164
 * chu_a - decode format A burst
1165
 */
1166
static void
1167
chu_a(
1168
  struct peer *peer,
1169
  int nchar
1170
  )
1171
0
{
1172
0
  struct refclockproc *pp;
1173
0
  struct chuunit *up;
1174
1175
0
  char  tbuf[80]; /* trace buffer */
1176
0
  char *  p;
1177
0
  size_t  chars;
1178
0
  size_t  cb;
1179
0
  l_fp  offset;   /* timestamp offset */
1180
0
  int val;    /* distance */
1181
0
  int temp;
1182
0
  int i, j, k;
1183
1184
0
  pp = peer->procptr;
1185
0
  up = pp->unitptr;
1186
1187
  /*
1188
   * Determine correct burst phase. There are three cases
1189
   * corresponding to in-phase, one character early or one
1190
   * character late. These cases are distinguished by the position
1191
   * of the framing digits 0x6 at positions 0 and 5 and 0x3 at
1192
   * positions 4 and 9. The correct phase is when the distance
1193
   * relative to the framing digits is maximum. The burst is valid
1194
   * only if the maximum distance is at least MINSYNC.
1195
   */
1196
0
  up->syndist = k = 0;
1197
  // val = -16;
1198
0
  for (i = -1; i < 2; i++) {
1199
0
    temp = up->cbuf[i + 4] & 0xf;
1200
0
    if (i >= 0)
1201
0
      temp |= (up->cbuf[i] & 0xf) << 4;
1202
0
    val = chu_dist(temp, 0x63);
1203
0
    temp = (up->cbuf[i + 5] & 0xf) << 4;
1204
0
    if (i + 9 < nchar)
1205
0
      temp |= up->cbuf[i + 9] & 0xf;
1206
0
    val += chu_dist(temp, 0x63);
1207
0
    if (val > up->syndist) {
1208
0
      up->syndist = val;
1209
0
      k = i;
1210
0
    }
1211
0
  }
1212
1213
  /*
1214
   * Extract the second number; it must be in the range 2 through
1215
   * 9 and the two repititions must be the same.
1216
   */
1217
0
  temp = (up->cbuf[k + 4] >> 4) & 0xf;
1218
0
  if (temp < 2 || temp > 9 || k + 9 >= nchar || temp !=
1219
0
      ((up->cbuf[k + 9] >> 4) & 0xf))
1220
0
    temp = 0;
1221
0
  snprintf(tbuf, sizeof(tbuf),
1222
0
     "chuA %04x %4.0f %2d %2d %2d %2d %1d ", up->status,
1223
0
     up->maxsignal, nchar, up->burdist, k, up->syndist,
1224
0
     temp);
1225
0
  cb = sizeof(tbuf);
1226
0
  p = tbuf;
1227
0
  for (i = 0; i < nchar; i++) {
1228
0
    chars = strlen(p);
1229
0
    if (cb < chars + 1) {
1230
0
      msyslog(LOG_ERR, "chu_a() fatal out buffer");
1231
0
      exit(1);
1232
0
    }
1233
0
    cb -= chars;
1234
0
    p += chars;
1235
0
    snprintf(p, cb, "%02x", up->cbuf[i]);
1236
0
  }
1237
0
  if (pp->sloppyclockflag & CLK_FLAG4)
1238
0
    record_clock_stats(&peer->srcadr, tbuf);
1239
0
#ifdef DEBUG
1240
0
  if (debug)
1241
0
    printf("%s\n", tbuf);
1242
0
#endif
1243
0
  if (up->syndist < MINSYNC) {
1244
0
    up->status |= AFRAME;
1245
0
    return;
1246
0
  }
1247
1248
  /*
1249
   * A valid burst requires the first seconds number to match the
1250
   * last seconds number. If so, the burst timestamps are
1251
   * corrected to the current minute and saved for later
1252
   * processing. In addition, the seconds decode is advanced from
1253
   * the previous burst to the current one.
1254
   */
1255
0
  if (temp == 0) {
1256
0
    up->status |= AFORMAT;
1257
0
  } else {
1258
0
    up->status |= AVALID;
1259
0
    up->second = pp->second = 30 + temp;
1260
0
    offset.l_ui = 30 + temp;
1261
0
    offset.l_uf = 0;
1262
0
    i = 0;
1263
0
    if (k < 0)
1264
0
      offset = up->charstamp;
1265
0
    else if (k > 0)
1266
0
      i = 1;
1267
0
    for (; i < nchar && (i - 10) < k; i++) {
1268
0
      up->tstamp[up->ntstamp] = up->cstamp[i];
1269
0
      L_SUB(&up->tstamp[up->ntstamp], &offset);
1270
0
      L_ADD(&offset, &up->charstamp);
1271
0
      if (up->ntstamp < MAXSTAGE - 1)
1272
0
        up->ntstamp++;
1273
0
    }
1274
0
    while (temp > up->prevsec) {
1275
0
      for (j = 15; j > 0; j--) {
1276
0
        up->decode[9][j] = up->decode[9][j - 1];
1277
0
        up->decode[19][j] =
1278
0
            up->decode[19][j - 1];
1279
0
      }
1280
0
      up->decode[9][j] = up->decode[19][j] = 0;
1281
0
      up->prevsec++;
1282
0
    }
1283
0
  }
1284
1285
  /*
1286
   * Stash the data in the decoding matrix.
1287
   */
1288
0
  i = -(2 * k);
1289
0
  for (j = 0; j < nchar; j++) {
1290
0
    if (i < 0 || i > 18) {
1291
0
      i += 2;
1292
0
      continue;
1293
0
    }
1294
0
    up->decode[i][up->cbuf[j] & 0xf]++;
1295
0
    i++;
1296
0
    up->decode[i][(up->cbuf[j] >> 4) & 0xf]++;
1297
0
    i++;
1298
0
  }
1299
0
  up->burstcnt++;
1300
0
}
1301
1302
1303
/*
1304
 * chu_poll - called by the transmit procedure
1305
 */
1306
static void
1307
chu_poll(
1308
  int unit,
1309
  struct peer *peer /* peer structure pointer */
1310
  )
1311
0
{
1312
0
  struct refclockproc *pp;
1313
1314
0
  pp = peer->procptr;
1315
0
  pp->polls++;
1316
0
}
1317
1318
1319
/*
1320
 * chu_second - process minute data
1321
 */
1322
static void
1323
chu_second(
1324
  int unit,
1325
  struct peer *peer /* peer structure pointer */
1326
  )
1327
0
{
1328
0
  struct refclockproc *pp;
1329
0
  struct chuunit *up;
1330
0
  l_fp  offset;
1331
0
  char  synchar, qual, leapchar;
1332
0
  int minset, i;
1333
0
  double  dtemp;
1334
1335
0
  pp = peer->procptr;
1336
0
  up = pp->unitptr;
1337
1338
  /*
1339
   * This routine is called once per minute to process the
1340
   * accumulated burst data. We do a bit of fancy footwork so that
1341
   * this doesn't run while burst data are being accumulated.
1342
   */
1343
0
  up->second = (up->second + 1) % 60;
1344
0
  if (up->second != 0)
1345
0
    return;
1346
1347
  /*
1348
   * Process the last burst, if still in the burst buffer.
1349
   * If the minute contains a valid B frame with sufficient A
1350
   * frame metric, it is considered valid. However, the timecode
1351
   * is sent to clockstats even if invalid.
1352
   */
1353
0
  chu_burst(peer);
1354
0
  minset = ((current_time - peer->update) + 30) / 60;
1355
0
  dtemp = chu_major(peer);
1356
0
  qual = 0;
1357
0
  if (up->status & (BFRAME | AFRAME))
1358
0
    qual |= SYNERR;
1359
0
  if (up->status & (BFORMAT | AFORMAT))
1360
0
    qual |= FMTERR;
1361
0
  if (up->status & DECODE)
1362
0
    qual |= DECERR;
1363
0
  if (up->status & STAMP)
1364
0
    qual |= TSPERR;
1365
0
  if (up->status & BVALID && dtemp >= MINMETRIC)
1366
0
    up->status |= INSYNC;
1367
0
  synchar = leapchar = ' ';
1368
0
  if (!(up->status & INSYNC)) {
1369
0
    pp->leap = LEAP_NOTINSYNC;
1370
0
    synchar = '?';
1371
0
  } else if (up->leap & 0x2) {
1372
0
    pp->leap = LEAP_ADDSECOND;
1373
0
    leapchar = 'L';
1374
0
  } else if (up->leap & 0x4) {
1375
0
    pp->leap = LEAP_DELSECOND;
1376
0
    leapchar = 'l';
1377
0
  } else {
1378
0
    pp->leap = LEAP_NOWARNING;
1379
0
  }
1380
0
  snprintf(pp->a_lastcode, sizeof(pp->a_lastcode),
1381
0
      "%c%1X %04d %03d %02d:%02d:%02d %c%x %+d %d %d %s %.0f %d",
1382
0
      synchar, qual, pp->year, pp->day, pp->hour, pp->minute,
1383
0
      pp->second, leapchar, up->dst, up->dut, minset, up->gain,
1384
0
      up->ident, dtemp, up->ntstamp);
1385
0
  pp->lencode = strlen(pp->a_lastcode);
1386
1387
  /*
1388
   * If in sync and the signal metric is above threshold, the
1389
   * timecode is ipso fatso valid and can be selected to
1390
   * discipline the clock.
1391
   */
1392
0
  if (up->status & INSYNC && !(up->status & (DECODE | STAMP)) &&
1393
0
      dtemp > MINMETRIC) {
1394
0
    if (!clocktime(pp->day, pp->hour, pp->minute, 0, GMT,
1395
0
        up->tstamp[0].l_ui, &pp->yearstart, &offset.l_ui)) {
1396
0
      up->errflg = CEVNT_BADTIME;
1397
0
    } else {
1398
0
      offset.l_uf = 0;
1399
0
      for (i = 0; i < up->ntstamp; i++)
1400
0
        refclock_process_offset(pp, offset,
1401
0
        up->tstamp[i], PDELAY +
1402
0
            pp->fudgetime1);
1403
0
      pp->lastref = up->timestamp;
1404
0
      refclock_receive(peer);
1405
0
    }
1406
0
  }
1407
0
  if (dtemp > 0)
1408
0
    record_clock_stats(&peer->srcadr, pp->a_lastcode);
1409
0
#ifdef DEBUG
1410
0
  if (debug)
1411
0
    printf("chu: timecode %d %s\n", pp->lencode,
1412
0
        pp->a_lastcode);
1413
0
#endif
1414
0
#ifdef ICOM
1415
0
  chu_newchan(peer, dtemp);
1416
0
#endif /* ICOM */
1417
0
  chu_clear(peer);
1418
0
  if (up->errflg)
1419
0
    refclock_report(peer, up->errflg);
1420
0
  up->errflg = 0;
1421
0
}
1422
1423
1424
/*
1425
 * chu_major - majority decoder
1426
 */
1427
static double
1428
chu_major(
1429
  struct peer *peer /* peer structure pointer */
1430
  )
1431
0
{
1432
0
  struct refclockproc *pp;
1433
0
  struct chuunit *up;
1434
1435
0
  u_char  code[11]; /* decoded timecode */
1436
0
  int metric;   /* distance metric */
1437
0
  int val1;   /* maximum distance */
1438
0
  int synchar;  /* stray cat */
1439
0
  int temp;
1440
0
  int i, j, k;
1441
1442
0
  pp = peer->procptr;
1443
0
  up = pp->unitptr;
1444
1445
  /*
1446
   * Majority decoder. Each burst encodes two replications at each
1447
   * digit position in the timecode. Each row of the decoding
1448
   * matrix encodes the number of occurences of each digit found
1449
   * at the corresponding position. The maximum over all
1450
   * occurrences at each position is the distance for this
1451
   * position and the corresponding digit is the maximum-
1452
   * likelihood candidate. If the distance is not more than half
1453
   * the total number of occurences, a majority has not been found
1454
   * and the data are discarded. The decoding distance is defined
1455
   * as the sum of the distances over the first nine digits. The
1456
   * tenth digit varies over the seconds, so we don't count it.
1457
   */
1458
0
  metric = 0;
1459
0
  for (i = 0; i < 9; i++) {
1460
0
    val1 = 0;
1461
0
    k = 0;
1462
0
    for (j = 0; j < 16; j++) {
1463
0
      temp = up->decode[i][j] + up->decode[i + 10][j];
1464
0
      if (temp > val1) {
1465
0
        val1 = temp;
1466
0
        k = j;
1467
0
      }
1468
0
    }
1469
0
    if (val1 <= up->burstcnt)
1470
0
      up->status |= DECODE;
1471
0
    metric += val1;
1472
0
    code[i] = hexchar[k];
1473
0
  }
1474
1475
  /*
1476
   * Compute the timecode timestamp from the days, hours and
1477
   * minutes of the timecode. Use clocktime() for the aggregate
1478
   * minutes and the minute offset computed from the burst
1479
   * seconds. Note that this code relies on the filesystem time
1480
   * for the years and does not use the years of the timecode.
1481
   */
1482
0
  if (sscanf((char *)code, "%1x%3d%2d%2d", &synchar, &pp->day,
1483
0
      &pp->hour, &pp->minute) != 4)
1484
0
    up->status |= DECODE;
1485
0
  if (up->ntstamp < MINSTAMP)
1486
0
    up->status |= STAMP;
1487
0
  return (metric);
1488
0
}
1489
1490
1491
/*
1492
 * chu_clear - clear decoding matrix
1493
 */
1494
static void
1495
chu_clear(
1496
  struct peer *peer /* peer structure pointer */
1497
  )
1498
0
{
1499
0
  struct refclockproc *pp;
1500
0
  struct chuunit *up;
1501
0
  int i, j;
1502
1503
0
  pp = peer->procptr;
1504
0
  up = pp->unitptr;
1505
1506
  /*
1507
   * Clear stuff for the minute.
1508
   */
1509
0
  up->ndx = up->prevsec = 0;
1510
0
  up->burstcnt = up->ntstamp = 0;
1511
0
  up->status &= INSYNC | METRIC;
1512
0
  for (i = 0; i < 20; i++) {
1513
0
    for (j = 0; j < 16; j++)
1514
0
      up->decode[i][j] = 0;
1515
0
  }
1516
0
}
1517
1518
#ifdef ICOM
1519
/*
1520
 * chu_newchan - called once per minute to find the best channel;
1521
 * returns zero on success, nonzero if ICOM error.
1522
 */
1523
static int
1524
chu_newchan(
1525
  struct peer *peer,
1526
  double  met
1527
  )
1528
0
{
1529
0
  struct chuunit *up;
1530
0
  struct refclockproc *pp;
1531
0
  struct xmtr *sp;
1532
0
  int rval;
1533
0
  double  metric;
1534
0
  int i;
1535
1536
0
  pp = peer->procptr;
1537
0
  up = pp->unitptr;
1538
1539
  /*
1540
   * The radio can be tuned to three channels: 0 (3330 kHz), 1
1541
   * (7850 kHz) and 2 (14670 kHz). There are five one-minute
1542
   * dwells in each cycle. During the first dwell the radio is
1543
   * tuned to one of the three channels to measure the channel
1544
   * metric. The channel is selected as the one least recently
1545
   * measured. During the remaining four dwells the radio is tuned
1546
   * to the channel with the highest channel metric. 
1547
   */
1548
0
  if (up->fd_icom <= 0)
1549
0
    return (0);
1550
1551
  /*
1552
   * Update the current channel metric and age of all channels.
1553
   * Scan all channels for the highest metric.
1554
   */
1555
0
  sp = &up->xmtr[up->chan];
1556
0
  sp->metric -= sp->integ[sp->iptr];
1557
0
  sp->integ[sp->iptr] = met;
1558
0
  sp->metric += sp->integ[sp->iptr];
1559
0
  sp->probe = 0;
1560
0
  sp->iptr = (sp->iptr + 1) % ISTAGE;
1561
0
  metric = 0;
1562
0
  for (i = 0; i < NCHAN; i++) {
1563
0
    up->xmtr[i].probe++;
1564
0
    if (up->xmtr[i].metric > metric) {
1565
0
      up->status |= METRIC;
1566
0
      metric = up->xmtr[i].metric;
1567
0
      up->chan = i;
1568
0
    }
1569
0
  }
1570
1571
  /*
1572
   * Start the next dwell. If the first dwell or no stations have
1573
   * been heard, continue round-robin scan.
1574
   */
1575
0
  up->dwell = (up->dwell + 1) % DWELL;
1576
0
  if (up->dwell == 0 || metric == 0) {
1577
0
    rval = 0;
1578
0
    for (i = 0; i < NCHAN; i++) {
1579
0
      if (up->xmtr[i].probe > rval) {
1580
0
        rval = up->xmtr[i].probe;
1581
0
        up->chan = i;
1582
0
      }
1583
0
    }
1584
0
  }
1585
1586
  /* Retune the radio at each dwell in case somebody nudges the
1587
   * tuning knob.
1588
   */
1589
0
  rval = icom_freq(up->fd_icom, peer->ttl & 0x7f, qsy[up->chan] +
1590
0
      TUNE);
1591
0
  snprintf(up->ident, sizeof(up->ident), "CHU%d", up->chan);
1592
0
  memcpy(&pp->refid, up->ident, 4); 
1593
0
  memcpy(&peer->refid, up->ident, 4);
1594
0
  if (metric == 0 && up->status & METRIC) {
1595
0
    up->status &= ~METRIC;
1596
0
    refclock_report(peer, CEVNT_PROP);
1597
0
  } 
1598
0
  return (rval);
1599
0
}
1600
#endif /* ICOM */
1601
1602
1603
/*
1604
 * chu_dist - determine the distance of two octet arguments
1605
 */
1606
static int
1607
chu_dist(
1608
  int x,    /* an octet of bits */
1609
  int y   /* another octet of bits */
1610
  )
1611
0
{
1612
0
  int val;    /* bit count */ 
1613
0
  int temp;
1614
0
  int i;
1615
1616
  /*
1617
   * The distance is determined as the weight of the exclusive OR
1618
   * of the two arguments. The weight is determined by the number
1619
   * of one bits in the result. Each one bit increases the weight,
1620
   * while each zero bit decreases it.
1621
   */
1622
0
  temp = x ^ y;
1623
0
  val = 0;
1624
0
  for (i = 0; i < 8; i++) {
1625
0
    if ((temp & 0x1) == 0)
1626
0
      val++;
1627
0
    else
1628
0
      val--;
1629
0
    temp >>= 1;
1630
0
  }
1631
0
  return (val);
1632
0
}
1633
1634
1635
#ifdef HAVE_AUDIO
1636
/*
1637
 * chu_gain - adjust codec gain
1638
 *
1639
 * This routine is called at the end of each second. During the second
1640
 * the number of signal clips above the MAXAMP threshold (6000). If
1641
 * there are no clips, the gain is bumped up; if there are more than
1642
 * MAXCLP clips (100), it is bumped down. The decoder is relatively
1643
 * insensitive to amplitude, so this crudity works just peachy. The
1644
 * routine also jiggles the input port and selectively mutes the
1645
 */
1646
static void
1647
chu_gain(
1648
  struct peer *peer /* peer structure pointer */
1649
  )
1650
0
{
1651
0
  struct refclockproc *pp;
1652
0
  struct chuunit *up;
1653
1654
0
  pp = peer->procptr;
1655
0
  up = pp->unitptr;
1656
1657
  /*
1658
   * Apparently, the codec uses only the high order bits of the
1659
   * gain control field. Thus, it may take awhile for changes to
1660
   * wiggle the hardware bits.
1661
   */
1662
0
  if (up->clipcnt == 0) {
1663
0
    up->gain += 4;
1664
0
    if (up->gain > MAXGAIN)
1665
0
      up->gain = MAXGAIN;
1666
0
  } else if (up->clipcnt > MAXCLP) {
1667
0
    up->gain -= 4;
1668
0
    if (up->gain < 0)
1669
0
      up->gain = 0;
1670
0
  }
1671
0
  audio_gain(up->gain, up->mongain, up->port);
1672
0
  up->clipcnt = 0;
1673
0
}
1674
#endif /* HAVE_AUDIO */
1675
1676
1677
#else
1678
NONEMPTY_TRANSLATION_UNIT
1679
#endif /* REFCLOCK */