-
Notifications
You must be signed in to change notification settings - Fork 78
/
track.c
3772 lines (3242 loc) · 133 KB
/
track.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
// Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// track.c: aircraft state tracking
//
// Copyright (c) 2019 Michael Wolf <michael@mictronics.de>
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2014-2016 Oliver Jowett <oliver@mutability.co.uk>
//
// This file is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This file is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// This file incorporates work covered by the following copyright and
// license:
//
// Copyright (C) 2012 by Salvatore Sanfilippo <antirez@gmail.com>
//
// 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 "readsb.h"
uint32_t modeAC_count[4096];
uint32_t modeAC_lastcount[4096];
uint32_t modeAC_match[4096];
uint32_t modeAC_age[4096];
#define PPforward if (0) {fprintf(stderr, "%s %d\n", __FILE__, __LINE__);}
static void showPositionDebug(struct aircraft *a, struct modesMessage *mm, int64_t now, double bad_lat, double bad_lon);
static void position_bad(struct modesMessage *mm, struct aircraft *a);
static void calc_wind(struct aircraft *a, int64_t now);
static void calc_temp(struct aircraft *a, int64_t now);
static inline int declination(struct aircraft *a, double *dec, int64_t now);
static const char *source_string(datasource_t source);
static void incrementReliable(struct aircraft *a, struct modesMessage *mm, int64_t now, int odd);
static uint16_t simpleHash(uint64_t receiverId) {
uint16_t simpleHash = receiverId;
simpleHash ^= (uint16_t) (receiverId >> 16);
simpleHash ^= (uint16_t) (receiverId >> 32);
simpleHash ^= (uint16_t) (receiverId >> 48);
if (simpleHash == 0)
return 1;
return simpleHash;
}
static float knots_to_meterpersecond = (1852.0 / 3600.0);
static void calculateMessageRateGlobal(int64_t now) {
float sum = 0.0f;
float mult = REMOVE_STALE_INTERVAL / 1000.0f;
float multSum = 0.0f;
for (int k = 0; k < MESSAGE_RATE_CALC_POINTS; k++) {
sum += Modes.messageRateAcc[k] * mult;
multSum += mult;
mult *= 0.7f;
}
Modes.messageRate = sum / multSum * Modes.messageRateMult;
Modes.nextMessageRateCalc = now + REMOVE_STALE_INTERVAL;
memmove(&Modes.messageRateAcc[1], &Modes.messageRateAcc[0], sizeof(uint16_t) * (MESSAGE_RATE_CALC_POINTS - 1));
Modes.messageRateAcc[0] = 0;
//fprintf(stderr, "%.3f\n", Modes.messageRate);
}
static void calculateMessageRate(struct aircraft *a, int64_t now) {
float sum = 0.0f;
float mult = REMOVE_STALE_INTERVAL / 1000.0f;
float multSum = 0.0f;
for (int k = 0; k < MESSAGE_RATE_CALC_POINTS; k++) {
sum += a->messageRateAcc[k] * mult;
multSum += mult;
mult *= 0.7f;
}
a->messageRate = sum / multSum * Modes.messageRateMult;
a->nextMessageRateCalc = now + REMOVE_STALE_INTERVAL;
memmove(&a->messageRateAcc[1], &a->messageRateAcc[0], sizeof(uint16_t) * (MESSAGE_RATE_CALC_POINTS - 1));
a->messageRateAcc[0] = 0;
}
// Should we accept some new data from the given source?
// If so, update the validity and return 1
static int32_t currentReduceInterval(int64_t now) {
return Modes.net_output_beast_reduce_interval * (1 + (Modes.doubleBeastReduceIntervalUntil > now));
}
static inline int will_accept_data(data_validity *d, datasource_t source, struct modesMessage *mm, struct aircraft *a) {
int64_t now = mm->sysTimestamp;
if (source == SOURCE_INVALID) {
return 0;
}
if (now < d->updated) {
return 0;
}
if (source < d->source && now < d->updated + TRACK_STALE) {
return 0;
}
// this is a position and will be wholly reverted if it's not accepted
//int is_pos = (mm->sbs_pos_valid || mm->cpr_valid || d == &a->pos_reliable_valid || d == &a->position_valid || d == &a->cpr_odd_valid || d == &a->cpr_even_valid || d == &a->mlat_pos_valid);
int is_pos = (mm->sbs_pos_valid || mm->cpr_valid);
// if we have a jaero position, don't allow non-position data to have a lesser source
if (!is_pos && a->pos_reliable_valid.source == SOURCE_JAERO && source < SOURCE_JAERO) {
return 0;
}
// prevent JAERO from disrupting other data sources too quickly
if (source == SOURCE_JAERO && a->pos_reliable_valid.last_source != SOURCE_JAERO && now < d->updated + 7 * MINUTES) {
return 0;
}
// if we have recent data and a recent position, only accept data from the last couple receivers that contributed a position
// this hopefully reduces data jitter introduced by differing receiver latencies
// it's important to excluded data coming in alongside positions, that extra data if accepted is discarded via the scratch mechanism
if (Modes.netReceiverId && !is_pos && a->pos_reliable_valid.source >= SOURCE_TISB && now - d->updated < 5 * SECONDS && now - a->seenPosReliable < 2200 * MS) {
uint16_t hash = simpleHash(mm->receiverId);
uint32_t found = 0;
for (int i = 0; i < RECEIVERIDBUFFER; i++) {
found += (a->receiverIds[i] == hash);
}
if (!found) {
return 0;
}
}
if (0 && is_pos && a->addr == Modes.cpr_focus) {
//fprintf(stderr, "%d %p %p\n", mm->duplicate, d, &a->pos_reliable_valid);
fprintf(stderr, "%d %s", mm->duplicate, source_string(mm->source));
}
return 1;
}
static int accept_data(data_validity *d, datasource_t source, struct modesMessage *mm, struct aircraft *a, int reduce_often) {
if (!will_accept_data(d, source, mm, a)) {
return 0;
}
int64_t now = mm->sysTimestamp;
d->source = source;
if (unlikely(source == SOURCE_PRIO)) {
d->source = SOURCE_ADSB;
}
d->last_source = d->source;
d->updated = now;
d->stale = 0;
if (now > d->next_reduce_forward || mm->reduce_forward) {
int32_t reduceInterval = currentReduceInterval(now);
if (reduce_often == REDUCE_OFTEN) {
reduceInterval = reduceInterval * 3 / 4;
} else if (reduce_often == REDUCE_RARE) {
reduceInterval = reduceInterval * 4;
}
if (mm->cpr_valid && reduceInterval > 7000) {
// make sure global CPR stays possible even at high interval:
reduceInterval = 7000;
}
d->next_reduce_forward = now + reduceInterval;
mm->reduce_forward = 1;
PPforward;
}
return 1;
}
// Given two datasources, produce a third datasource for data combined from them.
static void combine_validity(data_validity *to, const data_validity *from1, const data_validity *from2, int64_t now) {
if (from1->source == SOURCE_INVALID) {
*to = *from2;
return;
}
if (from2->source == SOURCE_INVALID) {
*to = *from1;
return;
}
to->source = (from1->source < from2->source) ? from1->source : from2->source; // the worse of the two input sources
to->last_source = to->source;
to->updated = (from1->updated > from2->updated) ? from1->updated : from2->updated; // the *later* of the two update times
to->stale = (now > to->updated + TRACK_STALE);
}
static int compare_validity(const data_validity *lhs, const data_validity *rhs) {
if (!lhs->stale && lhs->source > rhs->source)
return 1;
else if (!rhs->stale && lhs->source < rhs->source)
return -1;
else if (lhs->updated >= rhs->updated)
return 1;
else if (lhs->updated < rhs->updated)
return -1;
else
return 0;
}
static void update_range_histogram(struct aircraft *a, int64_t now) {
double lat = a->lat;
double lon = a->lon;
double range = a->receiver_distance;
int rangeDirDirection = ((int) nearbyint(a->receiver_direction)) % RANGEDIRS_BUCKETS;
int rangeDirIval = (now * (RANGEDIRS_IVALS - 1) / Modes.range_outline_duration) % RANGEDIRS_IVALS;
if (rangeDirIval != Modes.lastRangeDirHour) {
//log_with_timestamp("rangeDirIval: %d", rangeDirIval);
// when the current interval changes, reset the data for it
memset(Modes.rangeDirs[rangeDirIval], 0, sizeof(Modes.rangeDirs[rangeDirIval]));
Modes.lastRangeDirHour = rangeDirIval;
}
struct distCoords *current = &(Modes.rangeDirs[rangeDirIval][rangeDirDirection]);
// if the position isn't proper reliable, only allow it if the range in that direction is increased by less than 25 nmi compared to the maximum of the last 24h
if (range > current->distance && (a->pos_reliable_odd < 2 || a->pos_reliable_even < 2)) {
float directionMax = 0;
for (int i = 0; i < RANGEDIRS_IVALS; i++) {
if (Modes.rangeDirs[i][rangeDirDirection].distance > directionMax)
directionMax = Modes.rangeDirs[i][rangeDirDirection].distance;
}
directionMax += 50.0f * 1852.0f; // allow 50 nmi more than recorded for that direction in the last 24h
if (range > directionMax && !Modes.debug_bogus && Modes.json_reliable > 0) {
return;
}
//fprintf(stderr, "actual %.1f max %.1f\n", range / 1852.0f, (directionMax / 1852.0f));
}
if (range > current->distance) {
current->distance = range;
current->lat = lat;
current->lon = lon;
if (trackDataValid(&a->baro_alt_valid) || !trackDataValid(&a->geom_alt_valid)) {
current->alt = a->baro_alt;
} else {
current->alt = a->geom_alt;
}
}
if (range > Modes.stats_current.distance_max)
Modes.stats_current.distance_max = range;
if (range < Modes.stats_current.distance_min)
Modes.stats_current.distance_min = range;
int bucket = round(range / Modes.maxRange * RANGE_BUCKET_COUNT);
if (bucket < 0)
bucket = 0;
else if (bucket >= RANGE_BUCKET_COUNT)
bucket = RANGE_BUCKET_COUNT - 1;
++Modes.stats_current.range_histogram[bucket];
}
static int cpr_duplicate_check(int64_t now, struct aircraft *a, struct modesMessage *mm) {
struct cpr_cache *cpr;
uint32_t inCache = 0;
uint32_t cpr_lat = mm->cpr_lat;
uint32_t cpr_lon = mm->cpr_lon;
uint64_t receiverId = mm->receiverId;
for (int i = 0; i < CPR_CACHE; i++) {
cpr = &a->cpr_cache[i];
if (
(
now - cpr->ts < 2 * SECONDS
&& cpr->cpr_lat == cpr_lat
&& cpr->cpr_lon == cpr_lon
&& cpr->receiverId != receiverId
)
) {
inCache += 1;
}
}
if (inCache > 0) {
mm->duplicate = 1;
return 1;
} else {
// CPR not yet known to cpr cache
a->cpr_cache_index = (a->cpr_cache_index + 1) % CPR_CACHE;
cpr = &a->cpr_cache[a->cpr_cache_index];
cpr->ts = now;
cpr->cpr_lat = cpr_lat;
cpr->cpr_lon = cpr_lon;
cpr->receiverId = receiverId;
return 0;
}
}
static int duplicate_check(int64_t now, struct aircraft *a, double new_lat, double new_lon, struct modesMessage *mm) {
if (mm->duplicate_checked || mm->duplicate) {
// already checked
return mm->duplicate;
}
mm->duplicate_checked = 1;
// if the last position is older than 2 seconds we don't consider it a duplicate
if (now > a->seen_pos + 2 * SECONDS) {
return 0;
}
// duplicate
if (a->lat == new_lat && a->lon == new_lon) {
mm->duplicate = 1;
return 1;
}
// if the previous position is older than 2 seconds we don't consider it a duplicate
if (now > a->prev_pos_time + 2 * SECONDS) {
return 0;
}
// duplicate (this happens either with some transponder or delayed data arrival due to odd / even CPR, not certain)
if (a->prev_lat == new_lat && a->prev_lon == new_lon) {
mm->duplicate = 1;
return 1;
}
return 0;
}
static int uat2esnt_duplicate(int64_t now, struct aircraft *a, struct modesMessage *mm) {
return (
mm->cpr_valid && mm->cpr_odd && mm->msgtype == 18
&& (mm->timestamp == MAGIC_UAT_TIMESTAMP || mm->timestamp == 0)
&& now - a->seenPosReliable < 2500
);
}
static int inDiscCache(int64_t now, struct aircraft *a, struct modesMessage *mm) {
struct cpr_cache *disc;
uint32_t inCache = 0;
uint32_t cpr_lat = mm->cpr_lat;
uint32_t cpr_lon = mm->cpr_lon;
uint64_t receiverId = mm->receiverId;
for (int i = 0; i < DISCARD_CACHE; i++) {
disc = &a->disc_cache[i];
// don't decrement pos_reliable if we already got the same bad position within the last second
// rate limit reliable decrement per receiver
if (
(
now - disc->ts < 4 * SECONDS
&& disc->cpr_lat == cpr_lat
&& disc->cpr_lon == cpr_lon
)
||
(
now - disc->ts < 300
&& disc->receiverId == receiverId
)
) {
inCache += 1;
}
}
if (inCache > 0) {
return 1;
} else {
return 0;
}
}
// return true if it's OK for the aircraft to have travelled from its last known position
// to a new position at (lat,lon,surface) at a time of now.
static int speed_check(struct aircraft *a, datasource_t source, double lat, double lon, struct modesMessage *mm, cpr_local_t cpr_local) {
int64_t now = mm->sysTimestamp;
int64_t elapsed = trackDataAge(now, &a->position_valid);
int receiverRangeExceeded = 0;
if (0 && mm->sbs_in && a->addr == Modes.cpr_focus) {
fprintf(stderr, ".");
}
if (duplicate_check(now, a, lat, lon, mm)) {
// don't use duplicate positions
mm->pos_ignore = 1;
// but count it as a received position towards receiver heuristics
if (!Modes.userLocationValid) {
receiverPositionReceived(a, mm, lat, lon, now);
}
if (elapsed > 200 && a->receiverId == mm->receiverId && (Modes.debug_cpr || Modes.debug_speed_check || a->addr == Modes.cpr_focus)) {
// let speed_check continue for displaying this duplicate (at least for non-aggregated receivers)
} else {
// omit rest of speed check to save on cycles
return 1;
}
}
if (0 && (a->prev_lat == lat && a->prev_lon == lon) && (Modes.debug_cpr || Modes.debug_speed_check || a->addr == Modes.cpr_focus)) {
fprintf(stderr, "%06x now - seen_pos %6.3f now - prev_pos_time %6.3f\n",
a->addr,
(now - a->seen_pos) / 1000.0,
(now - a->prev_pos_time) / 1000.0
);
}
if (mm->cpr_valid && inDiscCache(now, a, mm)) {
mm->in_disc_cache = 1;
}
float distance = -1;
float range = -1;
float speed = -1;
float transmitted_speed = -1;
float calc_track = -1;
int inrange;
int override = 0;
double oldLat = a->lat;
double oldLon = a->lon;
int surface = trackDataValid(&a->airground_valid)
&& a->airground == AG_GROUND
&& a->pos_surface
&& (!mm->cpr_valid || mm->cpr_type == CPR_SURFACE);
// json_reliable == -1 disables the speed check
if (Modes.json_reliable == -1 || mm->source == SOURCE_PRIO) {
override = 1;
} else if (bogus_lat_lon(lat, lon) ||
(mm->cpr_valid && mm->cpr_lat == 0 && mm->cpr_lon == 0)
|| (
mm->cpr_valid && (mm->cpr_lat == 0 || mm->cpr_lon == 0)
&& (a->position_valid.source < SOURCE_TISB || !posReliable(a))
)
) {
mm->pos_ignore = 1; // don't decrement pos_reliable
} else if (a->pos_reliable_odd < 0.01f || a->pos_reliable_even < 0.01f) {
override = 1;
} else if (now - a->position_valid.updated > POS_RELIABLE_TIMEOUT) {
override = 1; // no reference or older than 60 minutes, assume OK
} else if (source > a->position_valid.source && source > a->position_valid.last_source && source > a->pos_reliable_valid.source) {
override = 1; // data is better quality, OVERRIDE
} else if (source > a->position_valid.source && a->position_valid.source == SOURCE_INDIRECT) {
override = 1; // data is better quality, OVERRIDE
} else if (source <= SOURCE_MLAT && elapsed > 45 * SECONDS) {
override = 1;
} else if (a->addr == 0xa19b53) {
// Virgin SS2
override = 1;
}
if (mm->in_disc_cache) {
override = 0; // don't override if in discard cache
}
if (trackDataValid(&a->gs_valid)) {
// use the larger of the current and earlier speed
speed = (a->gs_last_pos > a->gs) ? a->gs_last_pos : a->gs;
// add 3 knots for every second we haven't known the speed and the position
speed = speed + (3 * trackDataAge(now, &a->gs_valid)/1000.0f) + (3 * trackDataAge(now, &a->position_valid)/1000.0f);
} else if (trackDataValid(&a->tas_valid)) {
speed = a->tas * 4 / 3;
} else if (trackDataValid(&a->ias_valid)) {
speed = a->ias * 2;
}
transmitted_speed = speed;
// find actual distance
distance = greatcircle(oldLat, oldLon, lat, lon, 0);
mm->distance_traveled = distance;
float track_diff = -1;
float track_bonus = 0;
int64_t track_max_age = 5 * SECONDS;
int64_t track_age = -1;
float track = -1;
if (trackDataAge(now, &a->track_valid) < track_max_age) {
track = a->track;
track_age = trackDataAge(now, &a->track_valid);
} else if (trackDataAge(now, &a->true_heading_valid) < track_max_age) {
track = a->true_heading;
track_age = trackDataAge(now, &a->true_heading_valid);
}
if (distance > 2.5f) {
calc_track = bearing(oldLat, oldLon, lat, lon);
mm->calculated_track = calc_track;
if (source != SOURCE_MLAT
&& track > -1
&& trackDataAge(now, &a->position_valid) < 7 * SECONDS
) {
track_diff = fabs(norm_diff(track - calc_track, 180));
}
}
if (track_diff > 70.0f && speed > 10) {
mm->trackUnreliable = +1;
} else if (track_diff > -1) {
mm->trackUnreliable = -1;
}
if (!posReliable(a)) {
// don't use track_diff for further calculations unless position is already reliable
track_diff = -1;
}
if (speed < 0 || a->speedUnreliable > 8) {
speed = surface ? 120 : 900; // guess
}
if (speed > 10 && track_diff > -1 && a->trackUnreliable < 8) {
track_bonus = speed * (90.0f - track_diff) / 90.0f;
track_bonus *= (surface ? 0.9f : 1.0f) * (1.0f - track_age / track_max_age);
if (a->gs < 10) {
// don't allow negative "bonus" below 10 knots speed
track_bonus = fmaxf(0.0f, track_bonus);
speed += 2;
}
speed += track_bonus;
if (track_diff > 160) {
mm->pos_old = 1; // don't decrement pos_reliable
}
// allow relatively big forward jumps
if (speed > 40 && track_diff < 10) {
range += 2e3;
}
} else {
// Work out a reasonable speed to use:
// current speed + 1/3
speed = speed * 1.3f;
}
if (surface) {
range += 10;
} else {
range += 30;
}
// same TCP packet (2 ms), two positions from same receiver id, allow plenty of extra range
if (elapsed < 2 && a->receiverId == mm->receiverId && source > SOURCE_MLAT) {
range += 500; // 500 m extra in this case
}
// cap speed at 2000 knots ..
speed = fmin(speed, 2000);
if (source == SOURCE_MLAT) {
speed *= 1.4;
speed += 50;
range += 250;
}
if (transmitted_speed < 0) {
mm->speedUnreliable = -1;
} else if (distance > 2.5f && (track_diff < 70 || track_diff == -1)) {
if (distance <= range + (((float) elapsed + 50.0f) * (1.0f / 1000.0f)) * (transmitted_speed * knots_to_meterpersecond)) {
mm->speedUnreliable = -1;
} else if (distance > range + (((float) elapsed + 400.0f) * (1.0f / 1000.0f)) * (transmitted_speed * knots_to_meterpersecond)) {
mm->speedUnreliable = +1;
}
}
// plus distance covered at the given speed for the elapsed time + 0.2 seconds.
range += (((float) elapsed + 200.0f) * (1.0f / 1000.0f)) * (speed * (1852.0f / 3600.0f));
inrange = (distance <= range);
// don't allow going backwards in the air contrary to good track information
// when only a short time has elapsed
// when the receiverId differs
// this mostly happens due to static range allowed
if (!surface && a->gs > 10 && track_diff > 135 && elapsed < 2 * SECONDS && trackDataAge(now, &a->track_valid) < 2 * SECONDS && a->receiverId != mm->receiverId) {
inrange = 0;
}
float backInTimeSeconds = 0;
if (!inrange && a->gs > 10 && track_diff > 135 && trackDataAge(now, &a->gs_valid) < 10 * SECONDS) {
backInTimeSeconds = distance / (a->gs * (1852.0f / 3600.0f));
}
if (!Modes.userLocationValid && (inrange || override)) {
if (receiverPositionReceived(a, mm, lat, lon, now) == RECEIVER_RANGE_BAD) {
// far outside receiver area
receiverRangeExceeded = 1;
}
}
if (!Modes.userLocationValid && !override && mm->source == SOURCE_ADSB) {
if (!receiverRangeExceeded && !inrange
&& (distance - range > 800 || backInTimeSeconds > 3) && track_diff > 45
&& a->pos_reliable_odd >= Modes.position_persistence * 3 / 4
&& a->pos_reliable_even >= Modes.position_persistence * 3 / 4
&& a->trackUnreliable < 3
) {
struct receiver *r = receiverBad(mm->receiverId, a->addr, now);
if (r && Modes.debug_garbage && r->badCounter > 6) {
fprintf(stderr, "hex: %06x id: %016"PRIx64" #good: %6d #bad: %3.0f trackDiff: %3.0f: %7.2fkm/%7.2fkm in %4.1f s, max %4.0f kt\n",
a->addr, r->id, r->goodCounter, r->badCounter,
track_diff,
distance / 1000.0,
range / 1000.0,
elapsed / 1000.0,
speed
);
}
}
}
if (
(
((!inrange && track_diff < 160) || (!surface && (a->speedUnreliable > 8 || a->trackUnreliable > 8)))
&& source == a->position_valid.source && source > SOURCE_MLAT && (Modes.debug_cpr || Modes.debug_speed_check)
)
|| (a->addr == Modes.cpr_focus && source >= a->position_valid.source)
|| (Modes.debug_maxRange && track_diff > 90)
|| (receiverRangeExceeded && Modes.debug_receiverRangeLimit)
) {
if (uat2esnt_duplicate(now, a, mm) || (!inrange && !override && mm->in_disc_cache) || mm->garbage) {
// don't show debug
} else {
char *failMessage;
if (inrange) {
failMessage = "pass";
} else if (override) {
failMessage = "ovrd";
} else if (receiverRangeExceeded) {
failMessage = "RcvR";
} else {
failMessage = "FAIL";
}
char uuid[32]; // needs 18 chars and null byte
sprint_uuid1(mm->receiverId, uuid);
fprintTime(stderr, now);
fprintf(stderr, " %06x R%3.1f|%3.1f %s %2.0f %s %s %s %4.0f%%%2ds%2dt %3.0f/%3.0f td %3.0f %8.3fkm in%4.1fs, %4.0fkt %11.6f,%11.6f->%11.6f,%11.6f biT %4.1f s %s rId %s\n",
a->addr,
a->pos_reliable_odd, a->pos_reliable_even,
mm->cpr_odd ? "O" : "E",
mm->cpr_odd ? fmin(99, (now - a->cpr_even_valid.updated) / 1000.0) : fmin(99, (now - a->cpr_odd_valid.updated) / 1000.0),
cpr_local == CPR_LOCAL ? "L" : (cpr_local == CPR_GLOBAL ? "G" : "S"),
(surface ? "S" : "A"),
failMessage,
fmin(9001.0, 100.0 * distance / range),
a->speedUnreliable,
a->trackUnreliable,
track,
calc_track,
track_diff,
fmin(9001.0, distance / 1000.0),
elapsed / 1000.0,
fmin(9001.0, distance / elapsed * 1000.0 / 1852.0 * 3600.0),
oldLat, oldLon, lat, lon,
backInTimeSeconds, source_string(mm->source), uuid);
}
}
// override, this allows for printing stuff instead of returning
if (override) {
if (!inrange) {
a->lastOverrideTs = now;
}
inrange = override;
}
if (receiverRangeExceeded && Modes.garbage_ports) {
mm->pos_receiver_range_exceeded = 1;
inrange = 0; // far outside receiver area
mm->pos_ignore = 1;
mm->pos_bad = 1;
}
return inrange;
}
/* debug code for surface CPR decoding ... might be useful and reduce typing at some point
if (Modes.debug_receiver && Modes.debug_speed_check && receiver && a->seen_pos
&& *lat < 89
&& *lat > -89
&& (fabs(a->lat - *lat) > 35 || fabs(a->lon - *lon) > 35 || fabs(reflat - *lat) > 35 || fabs(reflon - *lon) > 35)
&& !bogus_lat_lon(*lat, *lon)
) {
//struct receiver *r = receiver;
//fprintf(stderr, "id: %016"PRIx64" #pos: %9"PRIu64" lat min:%4.0f max:%4.0f lon min:%4.0f max:%4.0f\n",
// r->id, r->positionCounter,
// r->latMin, r->latMax,
// r->lonMin, r->lonMax);
int sc = speed_check(a, mm->source, *lat, *lon, mm, CPR_GLOBAL);
fprintf(stderr, "%s%06x surface CPR rec. ref.: %4.0f %4.0f sc: %d result: %7.2f %7.2f --> %7.2f %7.2f\n",
(a->addr & MODES_NON_ICAO_ADDRESS) ? "~" : " ",
a->addr, reflat, reflon, sc, a->lat, a->lon, *lat, *lon);
}
if (Modes.debug_receiver && receiver && a->addr == Modes.cpr_focus)
fprintf(stderr, "%06x using reference: %4.0f %4.0f result: %7.2f %7.2f\n", a->addr, reflat, reflon, *lat, *lon);
*/
static int doGlobalCPR(struct aircraft *a, struct modesMessage *mm, double *lat, double *lon, unsigned *nic, unsigned *rc) {
int result;
int fflag = mm->cpr_odd;
int surface = (mm->cpr_type == CPR_SURFACE);
struct receiver *receiver;
double reflat, reflon;
// derive NIC, Rc from the worse of the two position
// smaller NIC is worse; larger Rc is worse
*nic = (a->cpr_even_nic < a->cpr_odd_nic ? a->cpr_even_nic : a->cpr_odd_nic);
*rc = (a->cpr_even_rc > a->cpr_odd_rc ? a->cpr_even_rc : a->cpr_odd_rc);
if (surface) {
// surface global CPR
// find reference location
int ref = 0;
if (Modes.userLocationValid) {
reflat = Modes.fUserLat;
reflon = Modes.fUserLon;
ref = 1;
} else if ((receiver = receiverGetReference(mm->receiverId, &reflat, &reflon, a, 0))) {
//function sets reflat and reflon on success, nothing to do here.
ref = 2;
} else if (a->seen_pos && a->surfaceCPR_allow_ac_rel) {
reflat = a->latReliable;
reflon = a->lonReliable;
ref = 3;
} else {
// No local reference, give up
return (-1);
}
result = decodeCPRsurface(reflat, reflon,
a->cpr_even_lat, a->cpr_even_lon,
a->cpr_odd_lat, a->cpr_odd_lon,
fflag,
lat, lon);
double refDistance = greatcircle(reflat, reflon, *lat, *lon, 0);
if (refDistance > 450e3) {
if (0 && (a->addr == Modes.cpr_focus || Modes.debug_cpr)) {
fprintf(stderr, "%06x CPRsurface ref %d refDistance: %4.0f km (%4.0f, %4.0f) allow_ac_rel %d\n", a->addr, ref, refDistance / 1000.0, reflat, reflon, a->surfaceCPR_allow_ac_rel);
}
// change to failure which doesn't decrement reliable
result = -1;
return result;
}
} else {
// airborne global CPR
result = decodeCPRairborne(a->cpr_even_lat, a->cpr_even_lon,
a->cpr_odd_lat, a->cpr_odd_lon,
fflag,
lat, lon);
}
if (result < 0) {
if (!mm->duplicate && (a->addr == Modes.cpr_focus || Modes.debug_cpr) && !inDiscCache(mm->sysTimestamp, a, mm)) {
fprintf(stderr, "CPR: decode failure for %06x (%d): even: %d %d odd: %d %d fflag: %s\n",
a->addr, result,
a->cpr_even_lat, a->cpr_even_lon,
a->cpr_odd_lat, a->cpr_odd_lon,
fflag ? "odd" : "even");
}
return result;
}
// check max range
if (Modes.maxRange > 0 && Modes.userLocationValid) {
mm->receiver_distance = greatcircle(Modes.fUserLat, Modes.fUserLon, *lat, *lon, 0);
if (mm->receiver_distance > Modes.maxRange) {
if (a->addr == Modes.cpr_focus || Modes.debug_bogus) {
fprintf(stdout, "%5llu %5.1f Global range check failed: %06x %.3f,%.3f, max range %.1fkm, actual %.1fkm\n",
(long long) mm->timestamp % 65536,
10 * log10(mm->signalLevel),
a->addr, *lat, *lon, Modes.maxRange / 1000.0, mm->receiver_distance / 1000.0);
}
if (mm->source != SOURCE_MLAT) {
Modes.stats_current.cpr_global_range_checks++;
if (Modes.debug_maxRange) {
showPositionDebug(a, mm, mm->sysTimestamp, *lat, *lon);
}
}
return (-2); // we consider an out-of-range value to be bad data
}
}
// check speed limit
if (!speed_check(a, mm->source, *lat, *lon, mm, CPR_GLOBAL)) {
if (mm->source != SOURCE_MLAT)
Modes.stats_current.cpr_global_speed_checks++;
return -2;
}
return result;
}
static int doLocalCPR(struct aircraft *a, struct modesMessage *mm, double *lat, double *lon, unsigned *nic, unsigned *rc) {
// relative CPR
// find reference location
double reflat, reflon;
double range_limit = 0;
int result;
int fflag = mm->cpr_odd;
int surface = (mm->cpr_type == CPR_SURFACE);
int relative_to = 0; // aircraft(1) or receiver(2) relative
if (fflag) {
*nic = a->cpr_odd_nic;
*rc = a->cpr_odd_rc;
} else {
*nic = a->cpr_even_nic;
*rc = a->cpr_even_rc;
}
int64_t now = mm->sysTimestamp;
if (now < a->seenPosGlobal + 10 * MINUTES && a->localCPR_allow_ac_rel) {
reflat = a->lat;
reflon = a->lon;
if (a->pos_nic < *nic)
*nic = a->pos_nic;
if (a->pos_rc < *rc)
*rc = a->pos_rc;
range_limit = 1852*100; // 100NM
// 100 NM in the 10 minutes of position validity means 600 knots which
// is fast but happens even for commercial airliners.
// It's not a problem if this limitation fails every now and then.
// A wrong relative position decode would require the aircraft to
// travel 360-100=260 NM in the 10 minutes of position validity.
// This is impossible for planes slower than 1560 knots/Mach 2.3 over the ground.
// Thus this range limit combined with the 10 minutes of position
// validity should not provide bad positions (1 cell away).
relative_to = 1;
} else if (!surface && Modes.userLocationValid) {
reflat = Modes.fUserLat;
reflon = Modes.fUserLon;
// The cell size is at least 360NM, giving a nominal
// max range of 180NM (half a cell).
//
// If the receiver range is more than half a cell
// then we must limit this range further to avoid
// ambiguity. (e.g. if we receive a position report
// at 200NM distance, this may resolve to a position
// at (200-360) = 160NM in the wrong direction)
if (Modes.maxRange == 0) {
return (-1); // Can't do receiver-centered checks at all
} else if (Modes.maxRange <= 1852 * 180) {
range_limit = Modes.maxRange;
} else if (Modes.maxRange < 1852 * 360) {
range_limit = (1852 * 360) - Modes.maxRange;
} else {
return (-1); // Can't do receiver-centered checks at all
}
relative_to = 2;
} else {
// No local reference, give up
return (-1);
}
result = decodeCPRrelative(reflat, reflon,
mm->cpr_lat,
mm->cpr_lon,
fflag, surface,
lat, lon);
if (result < 0) {
return result;
}
// check range limit
if (range_limit > 0) {
double range = greatcircle(reflat, reflon, *lat, *lon, 0);
if (range > range_limit) {
if (mm->source != SOURCE_MLAT)
Modes.stats_current.cpr_local_range_checks++;
return (-1);
}
}
// check max range
if (Modes.maxRange > 0 && Modes.userLocationValid) {
mm->receiver_distance = greatcircle(Modes.fUserLat, Modes.fUserLon, *lat, *lon, 0);
if (mm->receiver_distance > Modes.maxRange) {
if (a->addr == Modes.cpr_focus || Modes.debug_bogus) {
fprintf(stdout, "%5llu %5.1f Global range check failed: %06x %.3f,%.3f, max range %.1fkm, actual %.1fkm\n",
(long long) mm->timestamp % 65536,
10 * log10(mm->signalLevel),
a->addr, *lat, *lon, Modes.maxRange / 1000.0, mm->receiver_distance / 1000.0);
}
if (mm->source != SOURCE_MLAT) {
Modes.stats_current.cpr_local_range_checks++;
if (Modes.debug_maxRange) {
showPositionDebug(a, mm, mm->sysTimestamp, *lat, *lon);
}
}
return (-2); // we consider an out-of-range value to be bad data
}
}
// check speed limit
if (!speed_check(a, mm->source, *lat, *lon, mm, CPR_LOCAL)) {
if (mm->source != SOURCE_MLAT)
Modes.stats_current.cpr_local_speed_checks++;
return -2;
}
return relative_to;
}
static int64_t time_between(int64_t t1, int64_t t2) {
if (t1 >= t2)
return t1 - t2;
else
return t2 - t1;
}
static void setPosition(struct aircraft *a, struct modesMessage *mm, int64_t now) {
if (0 && a->addr == Modes.cpr_focus) {
showPositionDebug(a, mm, now, 0, 0);
}
// if we get the same position again but from an inferior source, assume it's delayed and treat as duplicate
if (now < a->seen_pos + 10 * MINUTES && mm->source < a->position_valid.last_source && mm->distance_traveled < 20) {
if (a->addr == Modes.cpr_focus) {
fprintf(stderr, "%06x less than 20 m\n", a->addr);
}
mm->duplicate = 1;
mm->pos_ignore = 1;
}
if (duplicate_check(now, a, mm->decoded_lat, mm->decoded_lon, mm)) {
// don't use duplicate positions
mm->pos_ignore = 1;
}
if (bogus_lat_lon(mm->decoded_lat, mm->decoded_lon)) {
if (0 && (fabs(mm->decoded_lat) >= 90.0 || fabs(mm->decoded_lon) >= 180.0)) {
fprintf(stderr, "%06x lat,lon out of bounds: %.2f,%.2f source: %s\n", a->addr, mm->decoded_lat, mm->decoded_lon, source_enum_string(mm->source));
}
return;
}
// for UAT messages converted by uat2esnt each position becomes a odd / even message pair
// only update the position for the odd message if we've recently seen a reliable position
if (uat2esnt_duplicate(now, a, mm)) {
return;
}
Modes.stats_current.pos_by_type[mm->addrtype]++;
Modes.stats_current.pos_all++;