-
Notifications
You must be signed in to change notification settings - Fork 53
/
dcfd.c
1884 lines (1666 loc) · 44.3 KB
/
dcfd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* /src/NTP/REPOSITORY/ntp4-dev/parseutil/dcfd.c,v 4.18 2005/10/07 22:08:18 kardel RELEASE_20051008_A
*
* dcfd.c,v 4.18 2005/10/07 22:08:18 kardel RELEASE_20051008_A
*
* DCF77 100/200ms pulse synchronisation daemon program (via 50Baud serial line)
*
* Features:
* DCF77 decoding
* simple NTP loopfilter logic for local clock
* interactive display for debugging
*
* Lacks:
* Leap second handling (at that level you should switch to NTP Version 4 - really!)
*
* Copyright (c) 1995-2015 by Frank Kardel <kardel <AT> ntp.org>
* Copyright (c) 1989-1994 by Frank Kardel, Friedrich-Alexander Universitaet Erlangen-Nuernberg, Germany
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the author nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <syslog.h>
#include <time.h>
/*
* NTP compilation environment
*/
#include "ntp_stdlib.h"
#include "ntpd.h" /* indirectly include ntp.h to get YEAR_PIVOT Y2KFixes */
/*
* select which terminal handling to use (currently only SysV variants)
*/
#if defined(HAVE_TERMIOS_H) || defined(STREAM)
#include <termios.h>
#define TTY_GETATTR(_FD_, _ARG_) tcgetattr((_FD_), (_ARG_))
#define TTY_SETATTR(_FD_, _ARG_) tcsetattr((_FD_), TCSANOW, (_ARG_))
#else /* not HAVE_TERMIOS_H || STREAM */
# if defined(HAVE_TERMIO_H) || defined(HAVE_SYSV_TTYS)
# include <termio.h>
# define TTY_GETATTR(_FD_, _ARG_) ioctl((_FD_), TCGETA, (_ARG_))
# define TTY_SETATTR(_FD_, _ARG_) ioctl((_FD_), TCSETAW, (_ARG_))
# endif/* HAVE_TERMIO_H || HAVE_SYSV_TTYS */
#endif /* not HAVE_TERMIOS_H || STREAM */
#ifndef TTY_GETATTR
#include "Bletch: MUST DEFINE ONE OF 'HAVE_TERMIOS_H' or 'HAVE_TERMIO_H'"
#endif
#ifndef days_per_year
#define days_per_year(_x_) (((_x_) % 4) ? 365 : (((_x_) % 400) ? 365 : 366))
#endif
#define timernormalize(_a_) \
if ((_a_)->tv_usec >= 1000000) \
{ \
(_a_)->tv_sec += (_a_)->tv_usec / 1000000; \
(_a_)->tv_usec = (_a_)->tv_usec % 1000000; \
} \
if ((_a_)->tv_usec < 0) \
{ \
(_a_)->tv_sec -= 1 + (-(_a_)->tv_usec / 1000000); \
(_a_)->tv_usec = 999999 - (-(_a_)->tv_usec - 1); \
}
#ifdef timeradd
#undef timeradd
#endif
#define timeradd(_a_, _b_) \
(_a_)->tv_sec += (_b_)->tv_sec; \
(_a_)->tv_usec += (_b_)->tv_usec; \
timernormalize((_a_))
#ifdef timersub
#undef timersub
#endif
#define timersub(_a_, _b_) \
(_a_)->tv_sec -= (_b_)->tv_sec; \
(_a_)->tv_usec -= (_b_)->tv_usec; \
timernormalize((_a_))
/*
* debug macros
*/
#define PRINTF if (interactive) printf
#define LPRINTF if (interactive && loop_filter_debug) printf
#ifdef DEBUG
#define DPRINTF(_x_) LPRINTF _x_
#else
#define DPRINTF(_x_)
#endif
#ifdef DECL_ERRNO
extern int errno;
#endif
static char *revision = "4.18";
/*
* display received data (avoids also detaching from tty)
*/
static int interactive = 0;
/*
* display loopfilter (clock control) variables
*/
static int loop_filter_debug = 0;
/*
* do not set/adjust system time
*/
static int no_set = 0;
/*
* time that passes between start of DCF impulse and time stamping (fine
* adjustment) in microseconds (receiver/OS dependent)
*/
#define DEFAULT_DELAY 230000 /* rough estimate */
/*
* The two states we can be in - eithe we receive nothing
* usable or we have the correct time
*/
#define NO_SYNC 0x01
#define SYNC 0x02
static int sync_state = NO_SYNC;
static time_t last_sync;
static unsigned long ticks = 0;
static char pat[] = "-\\|/";
#define LINES (24-2) /* error lines after which the two headlines are repeated */
#define MAX_UNSYNC (10*60) /* allow synchronisation loss for 10 minutes */
#define NOTICE_INTERVAL (20*60) /* mention missing synchronisation every 20 minutes */
/*
* clock adjustment PLL - see NTP protocol spec (RFC1305) for details
*/
#define USECSCALE 10
#define TIMECONSTANT 2
#define ADJINTERVAL 0
#define FREQ_WEIGHT 18
#define PHASE_WEIGHT 7
#define MAX_DRIFT 0x3FFFFFFF
#define R_SHIFT(_X_, _Y_) (((_X_) < 0) ? -(-(_X_) >> (_Y_)) : ((_X_) >> (_Y_)))
static long max_adj_offset_usec = 128000;
static long clock_adjust = 0; /* current adjustment value (usec * 2^USECSCALE) */
static long accum_drift = 0; /* accumulated drift value (usec / ADJINTERVAL) */
static long adjustments = 0;
static char skip_adjust = 1; /* discard first adjustment (bad samples) */
/*
* DCF77 state flags
*/
#define DCFB_ANNOUNCE 0x0001 /* switch time zone warning (DST switch) */
#define DCFB_DST 0x0002 /* DST in effect */
#define DCFB_LEAP 0x0004 /* LEAP warning (1 hour prior to occurrence) */
#define DCFB_CALLBIT 0x0008 /* "call bit" used to signalize irregularities in the control facilities */
struct clocktime /* clock time broken up from time code */
{
long wday; /* Day of week: 1: Monday - 7: Sunday */
long day;
long month;
long year;
long hour;
long minute;
long second;
long usecond;
long utcoffset; /* in minutes */
long flags; /* current clock status (DCF77 state flags) */
};
typedef struct clocktime clocktime_t;
/*
* (usually) quick constant multiplications
*/
#ifndef TIMES10
#define TIMES10(_X_) (((_X_) << 3) + ((_X_) << 1)) /* *8 + *2 */
#endif
#ifndef TIMES24
#define TIMES24(_X_) (((_X_) << 4) + ((_X_) << 3)) /* *16 + *8 */
#endif
#ifndef TIMES60
#define TIMES60(_X_) ((((_X_) << 4) - (_X_)) << 2) /* *(16 - 1) *4 */
#endif
/*
* generic l_abs() function
*/
#define l_abs(_x_) (((_x_) < 0) ? -(_x_) : (_x_))
/*
* conversion related return/error codes
*/
#define CVT_MASK 0x0000000F /* conversion exit code */
#define CVT_NONE 0x00000001 /* format not applicable */
#define CVT_FAIL 0x00000002 /* conversion failed - error code returned */
#define CVT_OK 0x00000004 /* conversion succeeded */
#define CVT_BADFMT 0x00000010 /* general format error - (unparsable) */
#define CVT_BADDATE 0x00000020 /* invalid date */
#define CVT_BADTIME 0x00000040 /* invalid time */
/*
* DCF77 raw time code
*
* From "Zur Zeit", Physikalisch-Technische Bundesanstalt (PTB), Braunschweig
* und Berlin, Maerz 1989
*
* Timecode transmission:
* AM:
* time marks are send every second except for the second before the
* next minute mark
* time marks consist of a reduction of transmitter power to 25%
* of the nominal level
* the falling edge is the time indication (on time)
* time marks of a 100ms duration constitute a logical 0
* time marks of a 200ms duration constitute a logical 1
* FM:
* see the spec. (basically a (non-)inverted psuedo random phase shift)
*
* Encoding:
* Second Contents
* 0 - 10 AM: free, FM: 0
* 11 - 14 free
* 15 R - "call bit" used to signalize irregularities in the control facilities
* (until 2003 indicated transmission via alternate antenna)
* 16 A1 - expect zone change (1 hour before)
* 17 - 18 Z1,Z2 - time zone
* 0 0 illegal
* 0 1 MEZ (MET)
* 1 0 MESZ (MED, MET DST)
* 1 1 illegal
* 19 A2 - expect leap insertion/deletion (1 hour before)
* 20 S - start of time code (1)
* 21 - 24 M1 - BCD (lsb first) Minutes
* 25 - 27 M10 - BCD (lsb first) 10 Minutes
* 28 P1 - Minute Parity (even)
* 29 - 32 H1 - BCD (lsb first) Hours
* 33 - 34 H10 - BCD (lsb first) 10 Hours
* 35 P2 - Hour Parity (even)
* 36 - 39 D1 - BCD (lsb first) Days
* 40 - 41 D10 - BCD (lsb first) 10 Days
* 42 - 44 DW - BCD (lsb first) day of week (1: Monday -> 7: Sunday)
* 45 - 49 MO - BCD (lsb first) Month
* 50 MO0 - 10 Months
* 51 - 53 Y1 - BCD (lsb first) Years
* 54 - 57 Y10 - BCD (lsb first) 10 Years
* 58 P3 - Date Parity (even)
* 59 - usually missing (minute indication), except for leap insertion
*/
/*-----------------------------------------------------------------------
* conversion table to map DCF77 bit stream into data fields.
* Encoding:
* Each field of the DCF77 code is described with two adjacent entries in
* this table. The first entry specifies the offset into the DCF77 data stream
* while the length is given as the difference between the start index and
* the start index of the following field.
*/
static struct rawdcfcode
{
char offset; /* start bit */
} rawdcfcode[] =
{
{ 0 }, { 15 }, { 16 }, { 17 }, { 19 }, { 20 }, { 21 }, { 25 }, { 28 }, { 29 },
{ 33 }, { 35 }, { 36 }, { 40 }, { 42 }, { 45 }, { 49 }, { 50 }, { 54 }, { 58 }, { 59 }
};
/*-----------------------------------------------------------------------
* symbolic names for the fields of DCF77 describes in "rawdcfcode".
* see comment above for the structure of the DCF77 data
*/
#define DCF_M 0
#define DCF_R 1
#define DCF_A1 2
#define DCF_Z 3
#define DCF_A2 4
#define DCF_S 5
#define DCF_M1 6
#define DCF_M10 7
#define DCF_P1 8
#define DCF_H1 9
#define DCF_H10 10
#define DCF_P2 11
#define DCF_D1 12
#define DCF_D10 13
#define DCF_DW 14
#define DCF_MO 15
#define DCF_MO0 16
#define DCF_Y1 17
#define DCF_Y10 18
#define DCF_P3 19
/*-----------------------------------------------------------------------
* parity field table (same encoding as rawdcfcode)
* This table describes the sections of the DCF77 code that are
* parity protected
*/
static struct partab
{
char offset; /* start bit of parity field */
} partab[] =
{
{ 21 }, { 29 }, { 36 }, { 59 }
};
/*-----------------------------------------------------------------------
* offsets for parity field descriptions
*/
#define DCF_P_P1 0
#define DCF_P_P2 1
#define DCF_P_P3 2
/*-----------------------------------------------------------------------
* legal values for time zone information
*/
#define DCF_Z_MET 0x2
#define DCF_Z_MED 0x1
/*-----------------------------------------------------------------------
* symbolic representation if the DCF77 data stream
*/
static struct dcfparam
{
unsigned char onebits[60];
unsigned char zerobits[60];
} dcfparam =
{
"###############RADMLS1248124P124812P1248121241248112481248P", /* 'ONE' representation */
"--------------------s-------p------p----------------------p" /* 'ZERO' representation */
};
/*-----------------------------------------------------------------------
* extract a bitfield from DCF77 datastream
* All numeric fields are LSB first.
* buf holds a pointer to a DCF77 data buffer in symbolic
* representation
* idx holds the index to the field description in rawdcfcode
*/
static unsigned long
ext_bf(
register unsigned char *buf,
register int idx
)
{
register unsigned long sum = 0;
register int i, first;
first = rawdcfcode[idx].offset;
for (i = rawdcfcode[idx+1].offset - 1; i >= first; i--)
{
sum <<= 1;
sum |= (buf[i] != dcfparam.zerobits[i]);
}
return sum;
}
/*-----------------------------------------------------------------------
* check even parity integrity for a bitfield
*
* buf holds a pointer to a DCF77 data buffer in symbolic
* representation
* idx holds the index to the field description in partab
*/
static unsigned
pcheck(
register unsigned char *buf,
register int idx
)
{
register int i,last;
register unsigned psum = 1;
last = partab[idx+1].offset;
for (i = partab[idx].offset; i < last; i++)
psum ^= (buf[i] != dcfparam.zerobits[i]);
return psum;
}
/*-----------------------------------------------------------------------
* convert a DCF77 data buffer into wall clock time + flags
*
* buffer holds a pointer to a DCF77 data buffer in symbolic
* representation
* size describes the length of DCF77 information in bits (represented
* as chars in symbolic notation
* clock points to a wall clock time description of the DCF77 data (result)
*/
static unsigned long
convert_rawdcf(
unsigned char *buffer,
int size,
clocktime_t *clock_time
)
{
if (size < 57)
{
PRINTF("%-30s", "*** INCOMPLETE");
return CVT_NONE;
}
/*
* check Start and Parity bits
*/
if ((ext_bf(buffer, DCF_S) == 1) &&
pcheck(buffer, DCF_P_P1) &&
pcheck(buffer, DCF_P_P2) &&
pcheck(buffer, DCF_P_P3))
{
/*
* buffer OK - extract all fields and build wall clock time from them
*/
clock_time->flags = 0;
clock_time->usecond= 0;
clock_time->second = 0;
clock_time->minute = ext_bf(buffer, DCF_M10);
clock_time->minute = TIMES10(clock_time->minute) + ext_bf(buffer, DCF_M1);
clock_time->hour = ext_bf(buffer, DCF_H10);
clock_time->hour = TIMES10(clock_time->hour) + ext_bf(buffer, DCF_H1);
clock_time->day = ext_bf(buffer, DCF_D10);
clock_time->day = TIMES10(clock_time->day) + ext_bf(buffer, DCF_D1);
clock_time->month = ext_bf(buffer, DCF_MO0);
clock_time->month = TIMES10(clock_time->month) + ext_bf(buffer, DCF_MO);
clock_time->year = ext_bf(buffer, DCF_Y10);
clock_time->year = TIMES10(clock_time->year) + ext_bf(buffer, DCF_Y1);
clock_time->wday = ext_bf(buffer, DCF_DW);
/*
* determine offset to UTC by examining the time zone
*/
switch (ext_bf(buffer, DCF_Z))
{
case DCF_Z_MET:
clock_time->utcoffset = -60;
break;
case DCF_Z_MED:
clock_time->flags |= DCFB_DST;
clock_time->utcoffset = -120;
break;
default:
PRINTF("%-30s", "*** BAD TIME ZONE");
return CVT_FAIL|CVT_BADFMT;
}
/*
* extract various warnings from DCF77
*/
if (ext_bf(buffer, DCF_A1))
clock_time->flags |= DCFB_ANNOUNCE;
if (ext_bf(buffer, DCF_A2))
clock_time->flags |= DCFB_LEAP;
if (ext_bf(buffer, DCF_R))
clock_time->flags |= DCFB_CALLBIT;
return CVT_OK;
}
else
{
/*
* bad format - not for us
*/
PRINTF("%-30s", "*** BAD FORMAT (invalid/parity)");
return CVT_FAIL|CVT_BADFMT;
}
}
/*-----------------------------------------------------------------------
* raw dcf input routine - fix up 50 baud
* characters for 1/0 decision
*/
static unsigned long
cvt_rawdcf(
unsigned char *buffer,
int size,
clocktime_t *clock_time
)
{
register unsigned char *s = buffer;
register unsigned char *e = buffer + size;
register unsigned char *b = dcfparam.onebits;
register unsigned char *c = dcfparam.zerobits;
register unsigned rtc = CVT_NONE;
register unsigned int i, lowmax, highmax, cutoff, span;
#define BITS 9
unsigned char histbuf[BITS];
/*
* the input buffer contains characters with runs of consecutive
* bits set. These set bits are an indication of the DCF77 pulse
* length. We assume that we receive the pulse at 50 Baud. Thus
* a 100ms pulse would generate a 4 bit train (20ms per bit and
* start bit)
* a 200ms pulse would create all zeroes (and probably a frame error)
*
* The basic idea is that on corret reception we must have two
* maxima in the pulse length distribution histogram. (one for
* the zero representing pulses and one for the one representing
* pulses)
* There will always be ones in the datastream, thus we have to see
* two maxima.
* The best point to cut for a 1/0 decision is the minimum between those
* between the maxima. The following code tries to find this cutoff point.
*/
/*
* clear histogram buffer
*/
for (i = 0; i < BITS; i++)
{
histbuf[i] = 0;
}
cutoff = 0;
lowmax = 0;
/*
* convert sequences of set bits into bits counts updating
* the histogram alongway
*/
while (s < e)
{
register unsigned int ch = *s ^ 0xFF;
/*
* check integrity and update histogramm
*/
if (!((ch+1) & ch) || !*s)
{
/*
* character ok
*/
for (i = 0; ch; i++)
{
ch >>= 1;
}
*s = i;
histbuf[i]++;
cutoff += i;
lowmax++;
}
else
{
/*
* invalid character (no consecutive bit sequence)
*/
DPRINTF(("parse: cvt_rawdcf: character check for 0x%x@%ld FAILED\n",
(u_int)*s, (long)(s - buffer)));
*s = (unsigned char)~0;
rtc = CVT_FAIL|CVT_BADFMT;
}
s++;
}
/*
* first cutoff estimate (average bit count - must be between both
* maxima)
*/
if (lowmax)
{
cutoff /= lowmax;
}
else
{
cutoff = 4; /* doesn't really matter - it'll fail anyway, but gives error output */
}
DPRINTF(("parse: cvt_rawdcf: average bit count: %d\n", cutoff));
lowmax = 0; /* weighted sum */
highmax = 0; /* bitcount */
/*
* collect weighted sum of lower bits (left of initial guess)
*/
DPRINTF(("parse: cvt_rawdcf: histogram:"));
for (i = 0; i <= cutoff; i++)
{
lowmax += histbuf[i] * i;
highmax += histbuf[i];
DPRINTF((" %d", histbuf[i]));
}
DPRINTF((" <M>"));
/*
* round up
*/
lowmax += highmax / 2;
/*
* calculate lower bit maximum (weighted sum / bit count)
*
* avoid divide by zero
*/
if (highmax)
{
lowmax /= highmax;
}
else
{
lowmax = 0;
}
highmax = 0; /* weighted sum of upper bits counts */
cutoff = 0; /* bitcount */
/*
* collect weighted sum of lower bits (right of initial guess)
*/
for (; i < BITS; i++)
{
highmax+=histbuf[i] * i;
cutoff +=histbuf[i];
DPRINTF((" %d", histbuf[i]));
}
DPRINTF(("\n"));
/*
* determine upper maximum (weighted sum / bit count)
*/
if (cutoff)
{
highmax /= cutoff;
}
else
{
highmax = BITS-1;
}
/*
* following now holds:
* lowmax <= cutoff(initial guess) <= highmax
* best cutoff is the minimum nearest to higher bits
*/
/*
* find the minimum between lowmax and highmax (detecting
* possibly a minimum span)
*/
span = cutoff = lowmax;
for (i = lowmax; i <= highmax; i++)
{
if (histbuf[cutoff] > histbuf[i])
{
/*
* got a new minimum move beginning of minimum (cutoff) and
* end of minimum (span) there
*/
cutoff = span = i;
}
else
if (histbuf[cutoff] == histbuf[i])
{
/*
* minimum not better yet - but it spans more than
* one bit value - follow it
*/
span = i;
}
}
/*
* cutoff point for 1/0 decision is the middle of the minimum section
* in the histogram
*/
cutoff = (cutoff + span) / 2;
DPRINTF(("parse: cvt_rawdcf: lower maximum %d, higher maximum %d, cutoff %d\n", lowmax, highmax, cutoff));
/*
* convert the bit counts to symbolic 1/0 information for data conversion
*/
s = buffer;
while ((s < e) && *c && *b)
{
if (*s == (unsigned char)~0)
{
/*
* invalid character
*/
*s = '?';
}
else
{
/*
* symbolic 1/0 representation
*/
*s = (*s >= cutoff) ? *b : *c;
}
s++;
b++;
c++;
}
/*
* if everything went well so far return the result of the symbolic
* conversion routine else just the accumulated errors
*/
if (rtc != CVT_NONE)
{
PRINTF("%-30s", "*** BAD DATA");
}
return (rtc == CVT_NONE) ? convert_rawdcf(buffer, size, clock_time) : rtc;
}
/*-----------------------------------------------------------------------
* convert a wall clock time description of DCF77 to a Unix time (seconds
* since 1.1. 1970 UTC)
*/
static time_t
dcf_to_unixtime(
clocktime_t *clock_time,
unsigned *cvtrtc
)
{
#define SETRTC(_X_) { if (cvtrtc) *cvtrtc = (_X_); }
static int days_of_month[] =
{
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
register int i;
time_t t;
/*
* map 2 digit years to 19xx (DCF77 is a 20th century item)
*/
if ( clock_time->year < YEAR_PIVOT ) /* in case of Y2KFixes [ */
clock_time->year += 100; /* *year%100, make tm_year */
/* *(do we need this?) */
if ( clock_time->year < YEAR_BREAK ) /* (failsafe if) */
clock_time->year += 1900; /* Y2KFixes ] */
/*
* must have been a really bad year code - drop it
*/
if (clock_time->year < (YEAR_PIVOT + 1900) ) /* Y2KFixes */
{
SETRTC(CVT_FAIL|CVT_BADDATE);
return -1;
}
/*
* sorry, slow section here - but it's not time critical anyway
*/
/*
* calculate days since 1970 (watching leap years)
*/
t = julian0( clock_time->year ) - julian0( 1970 );
/* month */
if (clock_time->month <= 0 || clock_time->month > 12)
{
SETRTC(CVT_FAIL|CVT_BADDATE);
return -1; /* bad month */
}
/* adjust current leap year */
#if 0
if (clock_time->month < 3 && days_per_year(clock_time->year) == 366)
t--;
#endif
/*
* collect days from months excluding the current one
*/
for (i = 1; i < clock_time->month; i++)
{
t += days_of_month[i];
}
/* day */
if (clock_time->day < 1 || ((clock_time->month == 2 && days_per_year(clock_time->year) == 366) ?
clock_time->day > 29 : clock_time->day > days_of_month[clock_time->month]))
{
SETRTC(CVT_FAIL|CVT_BADDATE);
return -1; /* bad day */
}
/*
* collect days from date excluding the current one
*/
t += clock_time->day - 1;
/* hour */
if (clock_time->hour < 0 || clock_time->hour >= 24)
{
SETRTC(CVT_FAIL|CVT_BADTIME);
return -1; /* bad hour */
}
/*
* calculate hours from 1. 1. 1970
*/
t = TIMES24(t) + clock_time->hour;
/* min */
if (clock_time->minute < 0 || clock_time->minute > 59)
{
SETRTC(CVT_FAIL|CVT_BADTIME);
return -1; /* bad min */
}
/*
* calculate minutes from 1. 1. 1970
*/
t = TIMES60(t) + clock_time->minute;
/* sec */
/*
* calculate UTC in minutes
*/
t += clock_time->utcoffset;
if (clock_time->second < 0 || clock_time->second > 60) /* allow for LEAPs */
{
SETRTC(CVT_FAIL|CVT_BADTIME);
return -1; /* bad sec */
}
/*
* calculate UTC in seconds - phew !
*/
t = TIMES60(t) + clock_time->second;
/* done */
return t;
}
/*-----------------------------------------------------------------------
* cheap half baked 1/0 decision - for interactive operation only
*/
static char
type(
unsigned int c
)
{
c ^= 0xFF;
return (c > 0xF);
}
/*-----------------------------------------------------------------------
* week day representation
*/
static const char *wday[8] =
{
"??",
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa",
"Su"
};
/*-----------------------------------------------------------------------
* generate a string representation for a timeval
*/
static char *
pr_timeval(
struct timeval *val
)
{
static char buf[20];
if (val->tv_sec == 0)
snprintf(buf, sizeof(buf), "%c0.%06ld",
(val->tv_usec < 0) ? '-' : '+',
(long int)l_abs(val->tv_usec));
else
snprintf(buf, sizeof(buf), "%ld.%06ld",
(long int)val->tv_sec,
(long int)l_abs(val->tv_usec));
return buf;
}
/*-----------------------------------------------------------------------
* correct the current time by an offset by setting the time rigorously
*/
static void
set_time(
struct timeval *offset
)
{
struct timeval the_time;
if (no_set)
return;
LPRINTF("set_time: %s ", pr_timeval(offset));
syslog(LOG_NOTICE, "setting time (offset %s)", pr_timeval(offset));
if (gettimeofday(&the_time, 0L) == -1)
{
perror("gettimeofday()");
}
else
{
timeradd(&the_time, offset);
if (settimeofday(&the_time, 0L) == -1)
{
perror("settimeofday()");
}
}
}
/*-----------------------------------------------------------------------
* slew the time by a given offset
*/
static void
adj_time(
long offset
)
{
struct timeval time_offset;
if (no_set)
return;
time_offset.tv_sec = offset / 1000000;
time_offset.tv_usec = offset % 1000000;
LPRINTF("adj_time: %ld us ", (long int)offset);
if (adjtime(&time_offset, 0L) == -1)
perror("adjtime()");
}
/*-----------------------------------------------------------------------
* read in a possibly previously written drift value
*/
static void
read_drift(
const char *drift_file
)
{
FILE *df;
df = fopen(drift_file, "r");
if (df != NULL)
{
int idrift = 0, fdrift = 0;
if (2 != fscanf(df, "%4d.%03d", &idrift, &fdrift))
LPRINTF("read_drift: trouble reading drift file");
fclose(df);
LPRINTF("read_drift: %d.%03d ppm ", idrift, fdrift);
accum_drift = idrift << USECSCALE;
fdrift = (fdrift << USECSCALE) / 1000;
accum_drift += fdrift & (1<<USECSCALE);
LPRINTF("read_drift: drift_comp %ld ", (long int)accum_drift);