forked from MalcolmRobb/dump1090
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mode_s.c
2201 lines (1979 loc) · 88.8 KB
/
mode_s.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
// dump1090, a Mode S messages decoder for RTLSDR devices.
//
// Copyright (C) 2012 by Salvatore Sanfilippo <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT
// HOLDER 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.
//
#include "dump1090.h"
//
// ===================== Mode S detection and decoding ===================
//
// Parity table for MODE S Messages.
// The table contains 112 elements, every element corresponds to a bit set
// in the message, starting from the first bit of actual data after the
// preamble.
//
// For messages of 112 bit, the whole table is used.
// For messages of 56 bits only the last 56 elements are used.
//
// The algorithm is as simple as xoring all the elements in this table
// for which the corresponding bit on the message is set to 1.
//
// The latest 24 elements in this table are set to 0 as the checksum at the
// end of the message should not affect the computation.
//
// Note: this function can be used with DF11 and DF17, other modes have
// the CRC xored with the sender address as they are reply to interrogations,
// but a casual listener can't split the address from the checksum.
//
uint32_t modes_checksum_table[112] = {
0x3935ea, 0x1c9af5, 0xf1b77e, 0x78dbbf, 0xc397db, 0x9e31e9, 0xb0e2f0, 0x587178,
0x2c38bc, 0x161c5e, 0x0b0e2f, 0xfa7d13, 0x82c48d, 0xbe9842, 0x5f4c21, 0xd05c14,
0x682e0a, 0x341705, 0xe5f186, 0x72f8c3, 0xc68665, 0x9cb936, 0x4e5c9b, 0xd8d449,
0x939020, 0x49c810, 0x24e408, 0x127204, 0x093902, 0x049c81, 0xfdb444, 0x7eda22,
0x3f6d11, 0xe04c8c, 0x702646, 0x381323, 0xe3f395, 0x8e03ce, 0x4701e7, 0xdc7af7,
0x91c77f, 0xb719bb, 0xa476d9, 0xadc168, 0x56e0b4, 0x2b705a, 0x15b82d, 0xf52612,
0x7a9309, 0xc2b380, 0x6159c0, 0x30ace0, 0x185670, 0x0c2b38, 0x06159c, 0x030ace,
0x018567, 0xff38b7, 0x80665f, 0xbfc92b, 0xa01e91, 0xaff54c, 0x57faa6, 0x2bfd53,
0xea04ad, 0x8af852, 0x457c29, 0xdd4410, 0x6ea208, 0x375104, 0x1ba882, 0x0dd441,
0xf91024, 0x7c8812, 0x3e4409, 0xe0d800, 0x706c00, 0x383600, 0x1c1b00, 0x0e0d80,
0x0706c0, 0x038360, 0x01c1b0, 0x00e0d8, 0x00706c, 0x003836, 0x001c1b, 0xfff409,
0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000
};
uint32_t modesChecksum(unsigned char *msg, int bits) {
uint32_t crc = 0;
uint32_t rem = 0;
int offset = (bits == 112) ? 0 : (112-56);
uint8_t theByte = *msg;
uint32_t * pCRCTable = &modes_checksum_table[offset];
int j;
// We don't really need to include the checksum itself
bits -= 24;
for(j = 0; j < bits; j++) {
if ((j & 7) == 0)
theByte = *msg++;
// If bit is set, xor with corresponding table entry.
if (theByte & 0x80) {crc ^= *pCRCTable;}
pCRCTable++;
theByte = theByte << 1;
}
rem = (msg[0] << 16) | (msg[1] << 8) | msg[2]; // message checksum
return ((crc ^ rem) & 0x00FFFFFF); // 24 bit checksum syndrome.
}
//
//=========================================================================
//
// Given the Downlink Format (DF) of the message, return the message length in bits.
//
// All known DF's 16 or greater are long. All known DF's 15 or less are short.
// There are lots of unused codes in both category, so we can assume ICAO will stick to
// these rules, meaning that the most significant bit of the DF indicates the length.
//
int modesMessageLenByType(int type) {
return (type & 0x10) ? MODES_LONG_MSG_BITS : MODES_SHORT_MSG_BITS ;
}
//
//=========================================================================
//
// Try to fix single bit errors using the checksum. On success modifies
// the original buffer with the fixed version, and returns the position
// of the error bit. Otherwise if fixing failed -1 is returned.
/*
int fixSingleBitErrors(unsigned char *msg, int bits) {
int j;
unsigned char aux[MODES_LONG_MSG_BYTES];
memcpy(aux, msg, bits/8);
// Do not attempt to error correct Bits 0-4. These contain the DF, and must
// be correct because we can only error correct DF17
for (j = 5; j < bits; j++) {
int byte = j/8;
int bitmask = 1 << (7 - (j & 7));
aux[byte] ^= bitmask; // Flip j-th bit
if (0 == modesChecksum(aux, bits)) {
// The error is fixed. Overwrite the original buffer with the
// corrected sequence, and returns the error bit position
msg[byte] = aux[byte];
return (j);
}
aux[byte] ^= bitmask; // Flip j-th bit back again
}
return (-1);
}
*/
//=========================================================================
//
// Similar to fixSingleBitErrors() but try every possible two bit combination.
// This is very slow and should be tried only against DF17 messages that
// don't pass the checksum, and only in Aggressive Mode.
/*
int fixTwoBitsErrors(unsigned char *msg, int bits) {
int j, i;
unsigned char aux[MODES_LONG_MSG_BYTES];
memcpy(aux, msg, bits/8);
// Do not attempt to error correct Bits 0-4. These contain the DF, and must
// be correct because we can only error correct DF17
for (j = 5; j < bits; j++) {
int byte1 = j/8;
int bitmask1 = 1 << (7 - (j & 7));
aux[byte1] ^= bitmask1; // Flip j-th bit
// Don't check the same pairs multiple times, so i starts from j+1
for (i = j+1; i < bits; i++) {
int byte2 = i/8;
int bitmask2 = 1 << (7 - (i & 7));
aux[byte2] ^= bitmask2; // Flip i-th bit
if (0 == modesChecksum(aux, bits)) {
// The error is fixed. Overwrite the original buffer with
// the corrected sequence, and returns the error bit position
msg[byte1] = aux[byte1];
msg[byte2] = aux[byte2];
// We return the two bits as a 16 bit integer by shifting
// 'i' on the left. This is possible since 'i' will always
// be non-zero because i starts from j+1
return (j | (i << 8));
aux[byte2] ^= bitmask2; // Flip i-th bit back
}
aux[byte1] ^= bitmask1; // Flip j-th bit back
}
}
return (-1);
}
*/
//
//=========================================================================
//
// Code for introducing a less CPU-intensive method of correcting
// single bit errors.
//
// Makes use of the fact that the crc checksum is linear with respect to
// the bitwise xor operation, i.e.
// crc(m^e) = (crc(m)^crc(e)
// where m and e are the message resp. error bit vectors.
//
// Call crc(e) the syndrome.
//
// The code below works by precomputing a table of (crc(e), e) for all
// possible error vectors e (here only single bit and double bit errors),
// search for the syndrome in the table, and correct the then known error.
// The error vector e is represented by one or two bit positions that are
// changed. If a second bit position is not used, it is -1.
//
// Run-time is binary search in a sorted table, plus some constant overhead,
// instead of running through all possible bit positions (resp. pairs of
// bit positions).
//
struct errorinfo {
uint32_t syndrome; // CRC syndrome
int bits; // Number of bit positions to fix
int pos[MODES_MAX_BITERRORS]; // Bit positions corrected by this syndrome
};
#define NERRORINFO \
(MODES_LONG_MSG_BITS+MODES_LONG_MSG_BITS*(MODES_LONG_MSG_BITS-1)/2)
struct errorinfo bitErrorTable[NERRORINFO];
// Compare function as needed for stdlib's qsort and bsearch functions
int cmpErrorInfo(const void *p0, const void *p1) {
struct errorinfo *e0 = (struct errorinfo*)p0;
struct errorinfo *e1 = (struct errorinfo*)p1;
if (e0->syndrome == e1->syndrome) {
return 0;
} else if (e0->syndrome < e1->syndrome) {
return -1;
} else {
return 1;
}
}
//
//=========================================================================
//
// Compute the table of all syndromes for 1-bit and 2-bit error vectors
void modesInitErrorInfo() {
unsigned char msg[MODES_LONG_MSG_BYTES];
int i, j, n;
uint32_t crc;
n = 0;
memset(bitErrorTable, 0, sizeof(bitErrorTable));
memset(msg, 0, MODES_LONG_MSG_BYTES);
// Add all possible single and double bit errors
// don't include errors in first 5 bits (DF type)
for (i = 5; i < MODES_LONG_MSG_BITS; i++) {
int bytepos0 = (i >> 3);
int mask0 = 1 << (7 - (i & 7));
msg[bytepos0] ^= mask0; // create error0
crc = modesChecksum(msg, MODES_LONG_MSG_BITS);
bitErrorTable[n].syndrome = crc; // single bit error case
bitErrorTable[n].bits = 1;
bitErrorTable[n].pos[0] = i;
bitErrorTable[n].pos[1] = -1;
n += 1;
if (Modes.nfix_crc > 1) {
for (j = i+1; j < MODES_LONG_MSG_BITS; j++) {
int bytepos1 = (j >> 3);
int mask1 = 1 << (7 - (j & 7));
msg[bytepos1] ^= mask1; // create error1
crc = modesChecksum(msg, MODES_LONG_MSG_BITS);
if (n >= NERRORINFO) {
//fprintf(stderr, "Internal error, too many entries, fix NERRORINFO\n");
break;
}
bitErrorTable[n].syndrome = crc; // two bit error case
bitErrorTable[n].bits = 2;
bitErrorTable[n].pos[0] = i;
bitErrorTable[n].pos[1] = j;
n += 1;
msg[bytepos1] ^= mask1; // revert error1
}
}
msg[bytepos0] ^= mask0; // revert error0
}
qsort(bitErrorTable, NERRORINFO, sizeof(struct errorinfo), cmpErrorInfo);
// Test code: report if any syndrome appears at least twice. In this
// case the correction cannot be done without ambiguity.
// Tried it, does not happen for 1- and 2-bit errors.
/*
for (i = 1; i < NERRORINFO; i++) {
if (bitErrorTable[i-1].syndrome == bitErrorTable[i].syndrome) {
fprintf(stderr, "modesInitErrorInfo: Collision for syndrome %06x\n",
(int)bitErrorTable[i].syndrome);
}
}
for (i = 0; i < NERRORINFO; i++) {
printf("syndrome %06x bit0 %3d bit1 %3d\n",
bitErrorTable[i].syndrome,
bitErrorTable[i].pos0, bitErrorTable[i].pos1);
}
*/
}
//
//=========================================================================
//
// Search for syndrome in table and if an entry is found, flip the necessary
// bits. Make sure the indices fit into the array
// Additional parameter: fix only less than maxcorrected bits, and record
// fixed bit positions in corrected[]. This array can be NULL, otherwise
// must be of length at least maxcorrected.
// Return number of fixed bits.
//
int fixBitErrors(unsigned char *msg, int bits, int maxfix, char *fixedbits) {
struct errorinfo *pei;
struct errorinfo ei;
int bitpos, offset, res, i;
memset(&ei, 0, sizeof(struct errorinfo));
ei.syndrome = modesChecksum(msg, bits);
pei = bsearch(&ei, bitErrorTable, NERRORINFO,
sizeof(struct errorinfo), cmpErrorInfo);
if (pei == NULL) {
return 0; // No syndrome found
}
// Check if the syndrome fixes more bits than we allow
if (maxfix < pei->bits) {
return 0;
}
// Check that all bit positions lie inside the message length
offset = MODES_LONG_MSG_BITS-bits;
for (i = 0; i < pei->bits; i++) {
bitpos = pei->pos[i] - offset;
if ((bitpos < 0) || (bitpos >= bits)) {
return 0;
}
}
// Fix the bits
for (i = res = 0; i < pei->bits; i++) {
bitpos = pei->pos[i] - offset;
msg[bitpos >> 3] ^= (1 << (7 - (bitpos & 7)));
if (fixedbits) {
fixedbits[res++] = bitpos;
}
}
return res;
}
//
// ============================== Debugging =================================
//
// Helper function for dumpMagnitudeVector().
// It prints a single bar used to display raw signals.
//
// Since every magnitude sample is between 0-255, the function uses
// up to 63 characters for every bar. Every character represents
// a length of 4, 3, 2, 1, specifically:
//
// "O" is 4
// "o" is 3
// "-" is 2
// "." is 1
//
void dumpMagnitudeBar(int index, int magnitude) {
char *set = " .-o";
char buf[256];
int div = magnitude / 256 / 4;
int rem = magnitude / 256 % 4;
memset(buf,'O',div);
buf[div] = set[rem];
buf[div+1] = '\0';
if (index >= 0)
printf("[%.3d] |%-66s 0x%04X\n", index, buf, magnitude);
else
printf("[%.2d] |%-66s 0x%04X\n", index, buf, magnitude);
}
//
//=========================================================================
//
// Display an ASCII-art alike graphical representation of the undecoded
// message as a magnitude signal.
//
// The message starts at the specified offset in the "m" buffer.
// The function will display enough data to cover a short 56 bit message.
//
// If possible a few samples before the start of the messsage are included
// for context.
//
void dumpMagnitudeVector(uint16_t *m, uint32_t offset) {
uint32_t padding = 5; // Show a few samples before the actual start.
uint32_t start = (offset < padding) ? 0 : offset-padding;
uint32_t end = offset + (MODES_PREAMBLE_SAMPLES)+(MODES_SHORT_MSG_SAMPLES) - 1;
uint32_t j;
for (j = start; j <= end; j++) {
dumpMagnitudeBar(j-offset, m[j]);
}
}
//
//=========================================================================
//
// Produce a raw representation of the message as a Javascript file
// loadable by debug.html.
//
void dumpRawMessageJS(char *descr, unsigned char *msg,
uint16_t *m, uint32_t offset, int fixable, char *bitpos)
{
int padding = 5; // Show a few samples before the actual start.
int start = offset - padding;
int end = offset + (MODES_PREAMBLE_SAMPLES)+(MODES_LONG_MSG_SAMPLES) - 1;
FILE *fp;
int j;
MODES_NOTUSED(fixable);
if ((fp = fopen("frames.js","a")) == NULL) {
fprintf(stderr, "Error opening frames.js: %s\n", strerror(errno));
exit(1);
}
fprintf(fp,"frames.push({\"descr\": \"%s\", \"mag\": [", descr);
for (j = start; j <= end; j++) {
fprintf(fp,"%d", j < 0 ? 0 : m[j]);
if (j != end) fprintf(fp,",");
}
fprintf(fp,"], \"fix1\": %d, \"fix2\": %d, \"bits\": %d, \"hex\": \"",
bitpos[0], bitpos[1] , modesMessageLenByType(msg[0]>>3));
for (j = 0; j < MODES_LONG_MSG_BYTES; j++)
fprintf(fp,"\\x%02x",msg[j]);
fprintf(fp,"\"});\n");
fclose(fp);
}
//
//=========================================================================
//
// This is a wrapper for dumpMagnitudeVector() that also show the message
// in hex format with an additional description.
//
// descr is the additional message to show to describe the dump.
// msg points to the decoded message
// m is the original magnitude vector
// offset is the offset where the message starts
//
// The function also produces the Javascript file used by debug.html to
// display packets in a graphical format if the Javascript output was
// enabled.
//
void dumpRawMessage(char *descr, unsigned char *msg, uint16_t *m, uint32_t offset) {
int j;
int msgtype = msg[0] >> 3;
int fixable = 0;
char bitpos[MODES_MAX_BITERRORS];
for (j = 0; j < MODES_MAX_BITERRORS; j++) {
bitpos[j] = -1;
}
if (msgtype == 17) {
fixable = fixBitErrors(msg, MODES_LONG_MSG_BITS, MODES_MAX_BITERRORS, bitpos);
}
if (Modes.debug & MODES_DEBUG_JS) {
dumpRawMessageJS(descr, msg, m, offset, fixable, bitpos);
return;
}
printf("\n--- %s\n ", descr);
for (j = 0; j < MODES_LONG_MSG_BYTES; j++) {
printf("%02x",msg[j]);
if (j == MODES_SHORT_MSG_BYTES-1) printf(" ... ");
}
printf(" (DF %d, Fixable: %d)\n", msgtype, fixable);
dumpMagnitudeVector(m,offset);
printf("---\n\n");
}
//
//=========================================================================
//
// Code for testing the timing: run all possible 1- and 2-bit error
// the test message by all 1-bit errors. Run the old code against
// all of them, and new the code.
//
// Example measurements:
// Timing old vs. new crc correction code:
// Old code: 1-bit errors on 112 msgs: 3934 usecs
// New code: 1-bit errors on 112 msgs: 104 usecs
// Old code: 2-bit errors on 6216 msgs: 407743 usecs
// New code: 2-bit errors on 6216 msgs: 5176 usecs
// indicating a 37-fold resp. 78-fold improvement in speed for 1-bit resp.
// 2-bit error.
/*
unsigned char tmsg0[MODES_LONG_MSG_BYTES] = {
// Test data: first ADS-B message from testfiles/modes1.bin
0x8f, 0x4d, 0x20, 0x23, 0x58, 0x7f, 0x34, 0x5e,
0x35, 0x83, 0x7e, 0x22, 0x18, 0xb2
};
#define NTWOBITS (MODES_LONG_MSG_BITS*(MODES_LONG_MSG_BITS-1)/2)
unsigned char tmsg1[MODES_LONG_MSG_BITS][MODES_LONG_MSG_BYTES];
unsigned char tmsg2[NTWOBITS][MODES_LONG_MSG_BYTES];
// Init an array of cloned messages with all possible 1-bit errors present,
// applied to each message at the respective position
//
void inittmsg1() {
int i, bytepos, mask;
for (i = 0; i < MODES_LONG_MSG_BITS; i++) {
bytepos = i >> 3;
mask = 1 << (7 - (i & 7));
memcpy(&tmsg1[i][0], tmsg0, MODES_LONG_MSG_BYTES);
tmsg1[i][bytepos] ^= mask;
}
}
// Run sanity check on all but first 5 messages / bits, as those bits
// are not corrected.
//
void checktmsg1(FILE *out) {
int i, k;
uint32_t crc;
for (i = 5; i < MODES_LONG_MSG_BITS; i++) {
crc = modesChecksum(&tmsg1[i][0], MODES_LONG_MSG_BITS);
if (crc != 0) {
fprintf(out, "CRC not fixed for "
"positon %d\n", i);
fprintf(out, " MSG ");
for (k = 0; k < MODES_LONG_MSG_BYTES; k++) {
fprintf(out, "%02x", tmsg1[i][k]);
}
fprintf(out, "\n");
}
}
}
void inittmsg2() {
int i, j, n, bytepos0, bytepos1, mask0, mask1;
n = 0;
for (i = 0; i < MODES_LONG_MSG_BITS; i++) {
bytepos0 = i >> 3;
mask0 = 1 << (7 - (i & 7));
for (j = i+1; j < MODES_LONG_MSG_BITS; j++) {
bytepos1 = j >> 3;
mask1 = 1 << (7 - (j & 7));
memcpy(&tmsg2[n][0], tmsg0, MODES_LONG_MSG_BYTES);
tmsg2[n][bytepos0] ^= mask0;
tmsg2[n][bytepos1] ^= mask1;
n += 1;
}
}
}
long difftvusec(struct timeval *t0, struct timeval *t1) {
long res = 0;
res = t1->tv_usec-t0->tv_usec;
res += (t1->tv_sec-t0->tv_sec)*1000000L;
return res;
}
// the actual test code
void testAndTimeBitCorrection() {
struct timeval starttv, endtv;
int i;
// Run timing on 1-bit errors
printf("Timing old vs. new crc correction code:\n");
inittmsg1();
gettimeofday(&starttv, NULL);
for (i = 0; i < MODES_LONG_MSG_BITS; i++) {
fixSingleBitErrors(&tmsg1[i][0], MODES_LONG_MSG_BITS);
}
gettimeofday(&endtv, NULL);
printf(" Old code: 1-bit errors on %d msgs: %ld usecs\n",
MODES_LONG_MSG_BITS, difftvusec(&starttv, &endtv));
checktmsg1(stdout);
// Re-init
inittmsg1();
gettimeofday(&starttv, NULL);
for (i = 0; i < MODES_LONG_MSG_BITS; i++) {
fixBitErrors(&tmsg1[i][0], MODES_LONG_MSG_BITS, MODES_MAX_BITERRORS, NULL);
}
gettimeofday(&endtv, NULL);
printf(" New code: 1-bit errors on %d msgs: %ld usecs\n",
MODES_LONG_MSG_BITS, difftvusec(&starttv, &endtv));
checktmsg1(stdout);
// Run timing on 2-bit errors
inittmsg2();
gettimeofday(&starttv, NULL);
for (i = 0; i < NTWOBITS; i++) {
fixSingleBitErrors(&tmsg2[i][0], MODES_LONG_MSG_BITS);
}
gettimeofday(&endtv, NULL);
printf(" Old code: 2-bit errors on %d msgs: %ld usecs\n",
NTWOBITS, difftvusec(&starttv, &endtv));
// Re-init
inittmsg2();
gettimeofday(&starttv, NULL);
for (i = 0; i < NTWOBITS; i++) {
fixBitErrors(&tmsg2[i][0], MODES_LONG_MSG_BITS, MODES_MAX_BITERRORS, NULL);
}
gettimeofday(&endtv, NULL);
printf(" New code: 2-bit errors on %d msgs: %ld usecs\n",
NTWOBITS, difftvusec(&starttv, &endtv));
}
*/
//=========================================================================
//
// Hash the ICAO address to index our cache of MODES_ICAO_CACHE_LEN
// elements, that is assumed to be a power of two
//
uint32_t ICAOCacheHashAddress(uint32_t a) {
// The following three rounds wil make sure that every bit affects
// every output bit with ~ 50% of probability.
a = ((a >> 16) ^ a) * 0x45d9f3b;
a = ((a >> 16) ^ a) * 0x45d9f3b;
a = ((a >> 16) ^ a);
return a & (MODES_ICAO_CACHE_LEN-1);
}
//
//=========================================================================
//
// Add the specified entry to the cache of recently seen ICAO addresses.
// Note that we also add a timestamp so that we can make sure that the
// entry is only valid for MODES_ICAO_CACHE_TTL seconds.
//
void addRecentlySeenICAOAddr(uint32_t addr) {
uint32_t h = ICAOCacheHashAddress(addr);
Modes.icao_cache[h*2] = addr;
Modes.icao_cache[h*2+1] = (uint32_t) time(NULL);
}
//
//=========================================================================
//
// Returns 1 if the specified ICAO address was seen in a DF format with
// proper checksum (not xored with address) no more than * MODES_ICAO_CACHE_TTL
// seconds ago. Otherwise returns 0.
//
int ICAOAddressWasRecentlySeen(uint32_t addr) {
uint32_t h = ICAOCacheHashAddress(addr);
uint32_t a = Modes.icao_cache[h*2];
uint32_t t = Modes.icao_cache[h*2+1];
uint64_t tn = time(NULL);
return ( (a) && (a == addr) && ( (tn - t) <= MODES_ICAO_CACHE_TTL) );
}
//
//=========================================================================
//
// In the squawk (identity) field bits are interleaved as follows in
// (message bit 20 to bit 32):
//
// C1-A1-C2-A2-C4-A4-ZERO-B1-D1-B2-D2-B4-D4
//
// So every group of three bits A, B, C, D represent an integer from 0 to 7.
//
// The actual meaning is just 4 octal numbers, but we convert it into a hex
// number tha happens to represent the four octal numbers.
//
// For more info: http://en.wikipedia.org/wiki/Gillham_code
//
int decodeID13Field(int ID13Field) {
int hexGillham = 0;
if (ID13Field & 0x1000) {hexGillham |= 0x0010;} // Bit 12 = C1
if (ID13Field & 0x0800) {hexGillham |= 0x1000;} // Bit 11 = A1
if (ID13Field & 0x0400) {hexGillham |= 0x0020;} // Bit 10 = C2
if (ID13Field & 0x0200) {hexGillham |= 0x2000;} // Bit 9 = A2
if (ID13Field & 0x0100) {hexGillham |= 0x0040;} // Bit 8 = C4
if (ID13Field & 0x0080) {hexGillham |= 0x4000;} // Bit 7 = A4
//if (ID13Field & 0x0040) {hexGillham |= 0x0800;} // Bit 6 = X or M
if (ID13Field & 0x0020) {hexGillham |= 0x0100;} // Bit 5 = B1
if (ID13Field & 0x0010) {hexGillham |= 0x0001;} // Bit 4 = D1 or Q
if (ID13Field & 0x0008) {hexGillham |= 0x0200;} // Bit 3 = B2
if (ID13Field & 0x0004) {hexGillham |= 0x0002;} // Bit 2 = D2
if (ID13Field & 0x0002) {hexGillham |= 0x0400;} // Bit 1 = B4
if (ID13Field & 0x0001) {hexGillham |= 0x0004;} // Bit 0 = D4
return (hexGillham);
}
//
//=========================================================================
//
// Decode the 13 bit AC altitude field (in DF 20 and others).
// Returns the altitude, and set 'unit' to either MODES_UNIT_METERS or MDOES_UNIT_FEETS.
//
int decodeAC13Field(int AC13Field, int *unit) {
int m_bit = AC13Field & 0x0040; // set = meters, clear = feet
int q_bit = AC13Field & 0x0010; // set = 25 ft encoding, clear = Gillham Mode C encoding
if (!m_bit) {
*unit = MODES_UNIT_FEET;
if (q_bit) {
// N is the 11 bit integer resulting from the removal of bit Q and M
int n = ((AC13Field & 0x1F80) >> 2) |
((AC13Field & 0x0020) >> 1) |
(AC13Field & 0x000F);
// The final altitude is resulting number multiplied by 25, minus 1000.
return ((n * 25) - 1000);
} else {
// N is an 11 bit Gillham coded altitude
int n = ModeAToModeC(decodeID13Field(AC13Field));
if (n < -12) {n = 0;}
return (100 * n);
}
} else {
*unit = MODES_UNIT_METERS;
// TODO: Implement altitude when meter unit is selected
}
return 0;
}
//
//=========================================================================
//
// Decode the 12 bit AC altitude field (in DF 17 and others).
//
int decodeAC12Field(int AC12Field, int *unit) {
int q_bit = AC12Field & 0x10; // Bit 48 = Q
*unit = MODES_UNIT_FEET;
if (q_bit) {
/// N is the 11 bit integer resulting from the removal of bit Q at bit 4
int n = ((AC12Field & 0x0FE0) >> 1) |
(AC12Field & 0x000F);
// The final altitude is the resulting number multiplied by 25, minus 1000.
return ((n * 25) - 1000);
} else {
// Make N a 13 bit Gillham coded altitude by inserting M=0 at bit 6
int n = ((AC12Field & 0x0FC0) << 1) |
(AC12Field & 0x003F);
n = ModeAToModeC(decodeID13Field(n));
if (n < -12) {n = 0;}
return (100 * n);
}
}
//
//=========================================================================
//
// Decode the 7 bit ground movement field PWL exponential style scale
//
int decodeMovementField(int movement) {
int gspeed;
// Note : movement codes 0,125,126,127 are all invalid, but they are
// trapped for before this function is called.
if (movement > 123) gspeed = 199; // > 175kt
else if (movement > 108) gspeed = ((movement - 108) * 5) + 100;
else if (movement > 93) gspeed = ((movement - 93) * 2) + 70;
else if (movement > 38) gspeed = ((movement - 38) ) + 15;
else if (movement > 12) gspeed = ((movement - 11) >> 1) + 2;
else if (movement > 8) gspeed = ((movement - 6) >> 2) + 1;
else gspeed = 0;
return (gspeed);
}
//
//=========================================================================
//
// Capability table
char *ca_str[8] = {
/* 0 */ "Level 1 (Surveillance Only)",
/* 1 */ "Level 2 (DF0,4,5,11)",
/* 2 */ "Level 3 (DF0,4,5,11,20,21)",
/* 3 */ "Level 4 (DF0,4,5,11,20,21,24)",
/* 4 */ "Level 2+3+4 (DF0,4,5,11,20,21,24,code7 - is on ground)",
/* 5 */ "Level 2+3+4 (DF0,4,5,11,20,21,24,code7 - is airborne)",
/* 6 */ "Level 2+3+4 (DF0,4,5,11,20,21,24,code7)",
/* 7 */ "Level 7 ???"
};
// DF 18 Control field table.
char *cf_str[8] = {
/* 0 */ "ADS-B ES/NT device with ICAO 24-bit address",
/* 1 */ "ADS-B ES/NT device with other address",
/* 2 */ "Fine format TIS-B",
/* 3 */ "Coarse format TIS-B",
/* 4 */ "TIS-B management message",
/* 5 */ "TIS-B relay of ADS-B message with other address",
/* 6 */ "ADS-B rebroadcast using DF-17 message format",
/* 7 */ "Reserved"
};
// Flight status table
char *fs_str[8] = {
/* 0 */ "Normal, Airborne",
/* 1 */ "Normal, On the ground",
/* 2 */ "ALERT, Airborne",
/* 3 */ "ALERT, On the ground",
/* 4 */ "ALERT & Special Position Identification. Airborne or Ground",
/* 5 */ "Special Position Identification. Airborne or Ground",
/* 6 */ "Value 6 is not assigned",
/* 7 */ "Value 7 is not assigned"
};
// Emergency state table
// from https://www.ll.mit.edu/mission/aviation/publications/publication-files/atc-reports/Grappel_2007_ATC-334_WW-15318.pdf
// and 1090-DO-260B_FRAC
char *es_str[8] = {
/* 0 */ "No emergency",
/* 1 */ "General emergency (squawk 7700)",
/* 2 */ "Lifeguard/Medical",
/* 3 */ "Minimum fuel",
/* 4 */ "No communications (squawk 7600)",
/* 5 */ "Unlawful interference (squawk 7500)",
/* 6 */ "Downed Aircraft",
/* 7 */ "Reserved"
};
//
//=========================================================================
//
char *getMEDescription(int metype, int mesub) {
char *mename = "Unknown";
if (metype >= 1 && metype <= 4)
mename = "Aircraft Identification and Category";
else if (metype >= 5 && metype <= 8)
mename = "Surface Position";
else if (metype >= 9 && metype <= 18)
mename = "Airborne Position (Baro Altitude)";
else if (metype == 19 && mesub >=1 && mesub <= 4)
mename = "Airborne Velocity";
else if (metype >= 20 && metype <= 22)
mename = "Airborne Position (GNSS Height)";
else if (metype == 23 && mesub == 0)
mename = "Test Message";
else if (metype == 23 && mesub == 7)
mename = "Test Message -- Squawk";
else if (metype == 24 && mesub == 1)
mename = "Surface System Status";
else if (metype == 28 && mesub == 1)
mename = "Extended Squitter Aircraft Status (Emergency)";
else if (metype == 28 && mesub == 2)
mename = "Extended Squitter Aircraft Status (1090ES TCAS RA)";
else if (metype == 29 && (mesub == 0 || mesub == 1))
mename = "Target State and Status Message";
else if (metype == 31 && (mesub == 0 || mesub == 1))
mename = "Aircraft Operational Status Message";
return mename;
}
//
//=========================================================================
//
// Decode a raw Mode S message demodulated as a stream of bytes by detectModeS(),
// and split it into fields populating a modesMessage structure.
//
void decodeModesMessage(struct modesMessage *mm, unsigned char *msg) {
char *ais_charset = "?ABCDEFGHIJKLMNOPQRSTUVWXYZ????? ???????????????0123456789??????";
// Work on our local copy
memcpy(mm->msg, msg, MODES_LONG_MSG_BYTES);
msg = mm->msg;
// Get the message type ASAP as other operations depend on this
mm->msgtype = msg[0] >> 3; // Downlink Format
mm->msgbits = modesMessageLenByType(mm->msgtype);
mm->crc = modesChecksum(msg, mm->msgbits);
if ((mm->crc) && (Modes.nfix_crc) && ((mm->msgtype == 17) || (mm->msgtype == 18))) {
// if ((mm->crc) && (Modes.nfix_crc) && ((mm->msgtype == 11) || (mm->msgtype == 17))) {
//
// Fixing single bit errors in DF-11 is a bit dodgy because we have no way to
// know for sure if the crc is supposed to be 0 or not - it could be any value
// less than 80. Therefore, attempting to fix DF-11 errors can result in a
// multitude of possible crc solutions, only one of which is correct.
//
// We should probably perform some sanity checks on corrected DF-11's before
// using the results. Perhaps check the ICAO against known aircraft, and check
// IID against known good IID's. That's a TODO.
//
mm->correctedbits = fixBitErrors(msg, mm->msgbits, Modes.nfix_crc, mm->corrected);
// If we correct, validate ICAO addr to help filter birthday paradox solutions.
if (mm->correctedbits) {
uint32_t ulAddr = (msg[1] << 16) | (msg[2] << 8) | (msg[3]);
if (!ICAOAddressWasRecentlySeen(ulAddr))
mm->correctedbits = 0;
}
}
//
// Note that most of the other computation happens *after* we fix the
// single/two bit errors, otherwise we would need to recompute the fields again.
//
if (mm->msgtype == 11) { // DF 11
mm->iid = mm->crc;
mm->addr = (msg[1] << 16) | (msg[2] << 8) | (msg[3]);
mm->ca = (msg[0] & 0x07); // Responder capabilities
if ((mm->crcok = (0 == mm->crc))) {
// DF 11 : if crc == 0 try to populate our ICAO addresses whitelist.
addRecentlySeenICAOAddr(mm->addr);
} else if (mm->crc < 80) {
mm->crcok = ICAOAddressWasRecentlySeen(mm->addr);
if (mm->crcok) {
addRecentlySeenICAOAddr(mm->addr);
}
}
} else if (mm->msgtype == 17) { // DF 17
mm->addr = (msg[1] << 16) | (msg[2] << 8) | (msg[3]);
mm->ca = (msg[0] & 0x07); // Responder capabilities
if ((mm->crcok = (0 == mm->crc))) {
// DF 17 : if crc == 0 try to populate our ICAO addresses whitelist.
addRecentlySeenICAOAddr(mm->addr);
}
} else if (mm->msgtype == 18) { // DF 18
mm->addr = (msg[1] << 16) | (msg[2] << 8) | (msg[3]);
mm->ca = (msg[0] & 0x07); // Control Field
if ((mm->crcok = (0 == mm->crc))) {
// DF 18 : if crc == 0 try to populate our ICAO addresses whitelist.
addRecentlySeenICAOAddr(mm->addr);
}
} else { // All other DF's
// Compare the checksum with the whitelist of recently seen ICAO
// addresses. If it matches one, then declare the message as valid
mm->crcok = ICAOAddressWasRecentlySeen(mm->addr = mm->crc);
}
// If we're checking CRC and the CRC is invalid, then we can't trust any
// of the data contents, so save time and give up now.
if ((Modes.check_crc) && (!mm->crcok) && (!mm->correctedbits)) { return;}
// Fields for DF0, DF16
if (mm->msgtype == 0 || mm->msgtype == 16) {
if (msg[0] & 0x04) { // VS Bit
mm->bFlags |= MODES_ACFLAGS_AOG_VALID | MODES_ACFLAGS_AOG;
} else {
mm->bFlags |= MODES_ACFLAGS_AOG_VALID;
}
}
// Fields for DF11, DF17
if (mm->msgtype == 11 || mm->msgtype == 17) {
if (mm->ca == 4) {
mm->bFlags |= MODES_ACFLAGS_AOG_VALID | MODES_ACFLAGS_AOG;
} else if (mm->ca == 5) {
mm->bFlags |= MODES_ACFLAGS_AOG_VALID;
}
}
// Fields for DF5, DF21 = Gillham encoded Squawk
if (mm->msgtype == 5 || mm->msgtype == 21) {
int ID13Field = ((msg[2] << 8) | msg[3]) & 0x1FFF;
if (ID13Field) {
mm->bFlags |= MODES_ACFLAGS_SQUAWK_VALID;
mm->modeA = decodeID13Field(ID13Field);
}
}
// Fields for DF0, DF4, DF16, DF20 13 bit altitude
if (mm->msgtype == 0 || mm->msgtype == 4 ||
mm->msgtype == 16 || mm->msgtype == 20) {
int AC13Field = ((msg[2] << 8) | msg[3]) & 0x1FFF;
if (AC13Field) { // Only attempt to decode if a valid (non zero) altitude is present
mm->bFlags |= MODES_ACFLAGS_ALTITUDE_VALID;
mm->altitude = decodeAC13Field(AC13Field, &mm->unit);
}
}
// Fields for DF4, DF5, DF20, DF21
if ((mm->msgtype == 4) || (mm->msgtype == 20) ||
(mm->msgtype == 5) || (mm->msgtype == 21)) {
mm->bFlags |= MODES_ACFLAGS_FS_VALID;
mm->fs = msg[0] & 7; // Flight status for DF4,5,20,21
if (mm->fs <= 3) {
mm->bFlags |= MODES_ACFLAGS_AOG_VALID;
if (mm->fs & 1)
{mm->bFlags |= MODES_ACFLAGS_AOG;}
}
}
// Fields for DF17, DF18_CF0, DF18_CF1, DF18_CF6 squitters
if ( (mm->msgtype == 17)
|| ((mm->msgtype == 18) && ((mm->ca == 0) || (mm->ca == 1) || (mm->ca == 6)) )) {
int metype = mm->metype = msg[4] >> 3; // Extended squitter message type
int mesub = mm->mesub = (metype == 29 ? ((msg[4]&6)>>1) : (msg[4] & 7)); // Extended squitter message subtype
// Decode the extended squitter message
if (metype >= 1 && metype <= 4) { // Aircraft Identification and Category
uint32_t chars;
mm->bFlags |= MODES_ACFLAGS_CALLSIGN_VALID;
chars = (msg[5] << 16) | (msg[6] << 8) | (msg[7]);
mm->flight[3] = ais_charset[chars & 0x3F]; chars = chars >> 6;
mm->flight[2] = ais_charset[chars & 0x3F]; chars = chars >> 6;
mm->flight[1] = ais_charset[chars & 0x3F]; chars = chars >> 6;
mm->flight[0] = ais_charset[chars & 0x3F];
chars = (msg[8] << 16) | (msg[9] << 8) | (msg[10]);
mm->flight[7] = ais_charset[chars & 0x3F]; chars = chars >> 6;
mm->flight[6] = ais_charset[chars & 0x3F]; chars = chars >> 6;
mm->flight[5] = ais_charset[chars & 0x3F]; chars = chars >> 6;
mm->flight[4] = ais_charset[chars & 0x3F];
mm->flight[8] = '\0';
} else if (metype == 19) { // Airborne Velocity Message
// Presumably airborne if we get an Airborne Velocity Message
mm->bFlags |= MODES_ACFLAGS_AOG_VALID;
if ( (mesub >= 1) && (mesub <= 4) ) {
int vert_rate = ((msg[8] & 0x07) << 6) | (msg[9] >> 2);
if (vert_rate) {
--vert_rate;
if (msg[8] & 0x08)
{vert_rate = 0 - vert_rate;}
mm->vert_rate = vert_rate * 64;