Debian Codegraph @

track.c

raw symbols SCIP
1 // Part of dump1090, a Mode S message decoder for RTLSDR devices.
2 //
3 // track.c: aircraft state tracking
4 //
5 // Copyright (c) 2014-2016 Oliver Jowett <[email protected]>
6 //
7 // This file is free software: you may copy, redistribute and/or modify it
8 // under the terms of the GNU General Public License as published by the
9 // Free Software Foundation, either version 2 of the License, or (at your
10 // option) any later version.
11 //
12 // This file is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 // This file incorporates work covered by the following copyright and
21 // permission notice:
22 //
23 // Copyright (C) 2012 by Salvatore Sanfilippo <[email protected]>
24 //
25 // All rights reserved.
26 //
27 // Redistribution and use in source and binary forms, with or without
28 // modification, are permitted provided that the following conditions are
29 // met:
30 //
31 // * Redistributions of source code must retain the above copyright
32 // notice, this list of conditions and the following disclaimer.
33 //
34 // * Redistributions in binary form must reproduce the above copyright
35 // notice, this list of conditions and the following disclaimer in the
36 // documentation and/or other materials provided with the distribution.
37 //
38 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
39 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
40 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
41 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
42 // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
44 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
45 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
46 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
47 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
48 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
49
50 #include "dump1090.h"
51 #include <inttypes.h>
52
53 /* #define DEBUG_CPR_CHECKS */
54
55 //
56 // Return a new aircraft structure for the linked list of tracked
57 // aircraft
58 //
59 struct aircraft *trackCreateAircraft(struct modesMessage *mm) {
60 static struct aircraft zeroAircraft;
61 struct aircraft *a = (struct aircraft *) malloc(sizeof(*a));
62 int i;
63
64 // Default everything to zero/NULL
65 *a = zeroAircraft;
66
67 // Now initialise things that should not be 0/NULL to their defaults
68 a->addr = mm->addr;
69 a->addrtype = mm->addrtype;
70 for (i = 0; i < 8; ++i)
71 a->signalLevel[i] = 1e-5;
72 a->signalNext = 0;
73
74 // start off with the "last emitted" ACAS RA being blank (just the BDS 3,0
75 // or ES type code)
76 a->fatsv_emitted_bds_30[0] = 0x30;
77 a->fatsv_emitted_es_acas_ra[0] = 0xE2;
78
79 // mm->msgtype 32 is used to represent Mode A/C. These values can never change, so
80 // set them once here during initialisation, and don't bother to set them every
81 // time this ModeA/C is received again in the future
82 if (mm->msgtype == 32) {
83 a->modeACflags = MODEAC_MSG_FLAG;
84 if (!mm->altitude_valid) {
85 a->modeACflags |= MODEAC_MSG_MODEA_ONLY;
86 }
87 }
88
89 // Copy the first message so we can emit it later when a second message arrives.
90 a->first_message = *mm;
91
92 Modes.stats_current.unique_aircraft++;
93
94 return (a);
95 }
96
97 //
98 //=========================================================================
99 //
100 // Return the aircraft with the specified address, or NULL if no aircraft
101 // exists with this address.
102 //
103 struct aircraft *trackFindAircraft(uint32_t addr) {
104 struct aircraft *a = Modes.aircrafts;
105
106 while(a) {
107 if (a->addr == addr) return (a);
108 a = a->next;
109 }
110 return (NULL);
111 }
112
113 // Should we accept some new data from the given source?
114 // If so, update the validity and return 1
115 static int accept_data(data_validity *d, datasource_t source, uint64_t now)
116 {
117 if (source < d->source && now < d->stale)
118 return 0;
119
120 d->source = source;
121 d->updated = now;
122 d->stale = now + 60000;
123 d->expires = now + 70000;
124 return 1;
125 }
126
127 // Given two datasources, produce a third datasource for data combined from them.
128 static void combine_validity(data_validity *to, const data_validity *from1, const data_validity *from2) {
129 if (from1->source == SOURCE_INVALID) {
130 *to = *from2;
131 return;
132 }
133
134 if (from2->source == SOURCE_INVALID) {
135 *to = *from1;
136 return;
137 }
138
139 to->source = (from1->source < from2->source) ? from1->source : from2->source; // the worse of the two input sources
140 to->updated = (from1->updated > from2->updated) ? from1->updated : from2->updated; // the *later* of the two update times
141 to->stale = (from1->stale < from2->stale) ? from1->stale : from2->stale; // the earlier of the two stale times
142 to->expires = (from1->expires < from2->expires) ? from1->expires : from2->expires; // the earlier of the two expiry times
143 }
144
145 static int compare_validity(const data_validity *lhs, const data_validity *rhs, uint64_t now) {
146 if (now < lhs->stale && lhs->source > rhs->source)
147 return 1;
148 else if (now < rhs->stale && lhs->source < rhs->source)
149 return -1;
150 else if (lhs->updated > rhs->updated)
151 return 1;
152 else if (lhs->updated < rhs->updated)
153 return -1;
154 else
155 return 0;
156 }
157
158 //
159 // CPR position updating
160 //
161
162 // Distance between points on a spherical earth.
163 // This has up to 0.5% error because the earth isn't actually spherical
164 // (but we don't use it in situations where that matters)
165 static double greatcircle(double lat0, double lon0, double lat1, double lon1)
166 {
167 double dlat, dlon;
168
169 lat0 = lat0 * M_PI / 180.0;
170 lon0 = lon0 * M_PI / 180.0;
171 lat1 = lat1 * M_PI / 180.0;
172 lon1 = lon1 * M_PI / 180.0;
173
174 dlat = fabs(lat1 - lat0);
175 dlon = fabs(lon1 - lon0);
176
177 // use haversine for small distances for better numerical stability
178 if (dlat < 0.001 && dlon < 0.001) {
179 double a = sin(dlat/2) * sin(dlat/2) + cos(lat0) * cos(lat1) * sin(dlon/2) * sin(dlon/2);
180 return 6371e3 * 2 * atan2(sqrt(a), sqrt(1.0 - a));
181 }
182
183 // spherical law of cosines
184 return 6371e3 * acos(sin(lat0) * sin(lat1) + cos(lat0) * cos(lat1) * cos(dlon));
185 }
186
187 static void update_range_histogram(double lat, double lon)
188 {
189 if (Modes.stats_range_histo && (Modes.bUserFlags & MODES_USER_LATLON_VALID)) {
190 double range = greatcircle(Modes.fUserLat, Modes.fUserLon, lat, lon);
191 int bucket = round(range / Modes.maxRange * RANGE_BUCKET_COUNT);
192
193 if (bucket < 0)
194 bucket = 0;
195 else if (bucket >= RANGE_BUCKET_COUNT)
196 bucket = RANGE_BUCKET_COUNT-1;
197
198 ++Modes.stats_current.range_histogram[bucket];
199 }
200 }
201
202 // return true if it's OK for the aircraft to have travelled from its last known position
203 // to a new position at (lat,lon,surface) at a time of now.
204 static int speed_check(struct aircraft *a, double lat, double lon, uint64_t now, int surface)
205 {
206 uint64_t elapsed;
207 double distance;
208 double range;
209 int speed;
210 int inrange;
211
212 if (!trackDataValid(&a->position_valid))
213 return 1; // no reference, assume OK
214
215 elapsed = trackDataAge(&a->position_valid, now);
216
217 if (trackDataValid(&a->speed_valid))
218 speed = a->speed;
219 else if (trackDataValid(&a->speed_ias_valid))
220 speed = a->speed_ias * 4 / 3;
221 else if (trackDataValid(&a->speed_tas_valid))
222 speed = a->speed_tas * 4 / 3;
223 else
224 speed = surface ? 100 : 600; // guess
225
226 // Work out a reasonable speed to use:
227 // current speed + 1/3
228 // surface speed min 20kt, max 150kt
229 // airborne speed min 200kt, no max
230 speed = speed * 4 / 3;
231 if (surface) {
232 if (speed < 20)
233 speed = 20;
234 if (speed > 150)
235 speed = 150;
236 } else {
237 if (speed < 200)
238 speed = 200;
239 }
240
241 // 100m (surface) or 500m (airborne) base distance to allow for minor errors,
242 // plus distance covered at the given speed for the elapsed time + 1 second.
243 range = (surface ? 0.1e3 : 0.5e3) + ((elapsed + 1000.0) / 1000.0) * (speed * 1852.0 / 3600.0);
244
245 // find actual distance
246 distance = greatcircle(a->lat, a->lon, lat, lon);
247
248 inrange = (distance <= range);
249 #ifdef DEBUG_CPR_CHECKS
250 if (!inrange) {
251 fprintf(stderr, "Speed check failed: %06x: %.3f,%.3f -> %.3f,%.3f in %.1f seconds, max speed %d kt, range %.1fkm, actual %.1fkm\n",
252 a->addr, a->lat, a->lon, lat, lon, elapsed/1000.0, speed, range/1000.0, distance/1000.0);
253 }
254 #endif
255
256 return inrange;
257 }
258
259 static int doGlobalCPR(struct aircraft *a, struct modesMessage *mm, uint64_t now, double *lat, double *lon, unsigned *nuc)
260 {
261 int result;
262 int fflag = mm->cpr_odd;
263 int surface = (mm->cpr_type == CPR_SURFACE);
264
265 *nuc = (a->cpr_even_nuc < a->cpr_odd_nuc ? a->cpr_even_nuc : a->cpr_odd_nuc); // worst of the two positions
266
267 if (surface) {
268 // surface global CPR
269 // find reference location
270 double reflat, reflon;
271
272 if (trackDataValidEx(&a->position_valid, now, 50000, SOURCE_INVALID)) { // Ok to try aircraft relative first
273 reflat = a->lat;
274 reflon = a->lon;
275 if (a->pos_nuc < *nuc)
276 *nuc = a->pos_nuc;
277 } else if (Modes.bUserFlags & MODES_USER_LATLON_VALID) {
278 reflat = Modes.fUserLat;
279 reflon = Modes.fUserLon;
280 } else {
281 // No local reference, give up
282 return (-1);
283 }
284
285 result = decodeCPRsurface(reflat, reflon,
286 a->cpr_even_lat, a->cpr_even_lon,
287 a->cpr_odd_lat, a->cpr_odd_lon,
288 fflag,
289 lat, lon);
290 } else {
291 // airborne global CPR
292 result = decodeCPRairborne(a->cpr_even_lat, a->cpr_even_lon,
293 a->cpr_odd_lat, a->cpr_odd_lon,
294 fflag,
295 lat, lon);
296 }
297
298 if (result < 0) {
299 #ifdef DEBUG_CPR_CHECKS
300 fprintf(stderr, "CPR: decode failure for %06X (%d).\n", a->addr, result);
301 fprintf(stderr, " even: %d %d odd: %d %d fflag: %s\n",
302 a->cpr_even_lat, a->cpr_even_lon,
303 a->cpr_odd_lat, a->cpr_odd_lon,
304 fflag ? "odd" : "even");
305 #endif
306 return result;
307 }
308
309 // check max range
310 if (Modes.maxRange > 0 && (Modes.bUserFlags & MODES_USER_LATLON_VALID)) {
311 double range = greatcircle(Modes.fUserLat, Modes.fUserLon, *lat, *lon);
312 if (range > Modes.maxRange) {
313 #ifdef DEBUG_CPR_CHECKS
314 fprintf(stderr, "Global range check failed: %06x: %.3f,%.3f, max range %.1fkm, actual %.1fkm\n",
315 a->addr, *lat, *lon, Modes.maxRange/1000.0, range/1000.0);
316 #endif
317
318 Modes.stats_current.cpr_global_range_checks++;
319 return (-2); // we consider an out-of-range value to be bad data
320 }
321 }
322
323 // for mlat results, skip the speed check
324 if (mm->source == SOURCE_MLAT)
325 return result;
326
327 // check speed limit
328 if (trackDataValid(&a->position_valid) && a->pos_nuc >= *nuc && !speed_check(a, *lat, *lon, now, surface)) {
329 Modes.stats_current.cpr_global_speed_checks++;
330 return -2;
331 }
332
333 return result;
334 }
335
336 static int doLocalCPR(struct aircraft *a, struct modesMessage *mm, uint64_t now, double *lat, double *lon, unsigned *nuc)
337 {
338 // relative CPR
339 // find reference location
340 double reflat, reflon;
341 double range_limit = 0;
342 int result;
343 int fflag = mm->cpr_odd;
344 int surface = (mm->cpr_type == CPR_SURFACE);
345
346 *nuc = mm->cpr_nucp;
347
348 if (trackDataValidEx(&a->position_valid, now, 50000, SOURCE_INVALID)) {
349 reflat = a->lat;
350 reflon = a->lon;
351
352 if (a->pos_nuc < *nuc)
353 *nuc = a->pos_nuc;
354
355 range_limit = 50e3;
356 } else if (!surface && (Modes.bUserFlags & MODES_USER_LATLON_VALID)) {
357 reflat = Modes.fUserLat;
358 reflon = Modes.fUserLon;
359
360 // The cell size is at least 360NM, giving a nominal
361 // max range of 180NM (half a cell).
362 //
363 // If the receiver range is more than half a cell
364 // then we must limit this range further to avoid
365 // ambiguity. (e.g. if we receive a position report
366 // at 200NM distance, this may resolve to a position
367 // at (200-360) = 160NM in the wrong direction)
368
369 if (Modes.maxRange == 0) {
370 return (-1); // Can't do receiver-centered checks at all
371 } else if (Modes.maxRange <= 1852*180) {
372 range_limit = Modes.maxRange;
373 } else if (Modes.maxRange < 1852*360) {
374 range_limit = (1852*360) - Modes.maxRange;
375 } else {
376 return (-1); // Can't do receiver-centered checks at all
377 }
378 } else {
379 // No local reference, give up
380 return (-1);
381 }
382
383 result = decodeCPRrelative(reflat, reflon,
384 mm->cpr_lat,
385 mm->cpr_lon,
386 fflag, surface,
387 lat, lon);
388 if (result < 0) {
389 return result;
390 }
391
392 // check range limit
393 if (range_limit > 0) {
394 double range = greatcircle(reflat, reflon, *lat, *lon);
395 if (range > range_limit) {
396 Modes.stats_current.cpr_local_range_checks++;
397 return (-1);
398 }
399 }
400
401 // check speed limit
402 if (trackDataValid(&a->position_valid) && a->pos_nuc >= *nuc && !speed_check(a, *lat, *lon, now, surface)) {
403 #ifdef DEBUG_CPR_CHECKS
404 fprintf(stderr, "Speed check for %06X with local decoding failed\n", a->addr);
405 #endif
406 Modes.stats_current.cpr_local_speed_checks++;
407 return -1;
408 }
409
410 return 0;
411 }
412
413 static uint64_t time_between(uint64_t t1, uint64_t t2)
414 {
415 if (t1 >= t2)
416 return t1 - t2;
417 else
418 return t2 - t1;
419 }
420
421 static void updatePosition(struct aircraft *a, struct modesMessage *mm, uint64_t now)
422 {
423 int location_result = -1;
424 uint64_t max_elapsed;
425 double new_lat = 0, new_lon = 0;
426 unsigned new_nuc = 0;
427 int surface;
428
429 surface = (mm->cpr_type == CPR_SURFACE);
430
431 if (surface) {
432 ++Modes.stats_current.cpr_surface;
433
434 // Surface: 25 seconds if >25kt or speed unknown, 50 seconds otherwise
435 if (mm->speed_valid && mm->speed <= 25)
436 max_elapsed = 50000;
437 else
438 max_elapsed = 25000;
439 } else {
440 ++Modes.stats_current.cpr_airborne;
441
442 // Airborne: 10 seconds
443 max_elapsed = 10000;
444 }
445
446 // If we have enough recent data, try global CPR
447 if (trackDataValid(&a->cpr_odd_valid) && trackDataValid(&a->cpr_even_valid) &&
448 a->cpr_odd_valid.source == a->cpr_even_valid.source &&
449 a->cpr_odd_type == a->cpr_even_type &&
450 time_between(a->cpr_odd_valid.updated, a->cpr_even_valid.updated) <= max_elapsed) {
451
452 location_result = doGlobalCPR(a, mm, now, &new_lat, &new_lon, &new_nuc);
453
454 if (location_result == -2) {
455 #ifdef DEBUG_CPR_CHECKS
456 fprintf(stderr, "global CPR failure (invalid) for (%06X).\n", a->addr);
457 #endif
458 // Global CPR failed because the position produced implausible results.
459 // This is bad data. Discard both odd and even messages and wait for a fresh pair.
460 // Also disable aircraft-relative positions until we have a new good position (but don't discard the
461 // recorded position itself)
462 Modes.stats_current.cpr_global_bad++;
463 a->cpr_odd_valid.source = a->cpr_even_valid.source = a->position_valid.source = SOURCE_INVALID;
464
465 return;
466 } else if (location_result == -1) {
467 #ifdef DEBUG_CPR_CHECKS
468 if (mm->source == SOURCE_MLAT) {
469 fprintf(stderr, "CPR skipped from MLAT (%06X).\n", a->addr);
470 }
471 #endif
472 // No local reference for surface position available, or the two messages crossed a zone.
473 // Nonfatal, try again later.
474 Modes.stats_current.cpr_global_skipped++;
475 } else {
476 Modes.stats_current.cpr_global_ok++;
477 combine_validity(&a->position_valid, &a->cpr_even_valid, &a->cpr_odd_valid);
478 }
479 }
480
481 // Otherwise try relative CPR.
482 if (location_result == -1) {
483 location_result = doLocalCPR(a, mm, now, &new_lat, &new_lon, &new_nuc);
484
485 if (location_result < 0) {
486 Modes.stats_current.cpr_local_skipped++;
487 } else {
488 Modes.stats_current.cpr_local_ok++;
489 mm->cpr_relative = 1;
490
491 if (mm->cpr_odd) {
492 a->position_valid = a->cpr_odd_valid;
493 } else {
494 a->position_valid = a->cpr_even_valid;
495 }
496 }
497 }
498
499 if (location_result == 0) {
500 // If we sucessfully decoded, back copy the results to mm so that we can print them in list output
501 mm->cpr_decoded = 1;
502 mm->decoded_lat = new_lat;
503 mm->decoded_lon = new_lon;
504
505 // Update aircraft state
506 a->lat = new_lat;
507 a->lon = new_lon;
508 a->pos_nuc = new_nuc;
509
510 update_range_histogram(new_lat, new_lon);
511 }
512 }
513
514 //
515 //=========================================================================
516 //
517 // Receive new messages and update tracked aircraft state
518 //
519
520 struct aircraft *trackUpdateFromMessage(struct modesMessage *mm)
521 {
522 struct aircraft *a;
523 uint64_t now = mstime();
524
525 // Lookup our aircraft or create a new one
526 a = trackFindAircraft(mm->addr);
527 if (!a) { // If it's a currently unknown aircraft....
528 a = trackCreateAircraft(mm); // ., create a new record for it,
529 a->next = Modes.aircrafts; // .. and put it at the head of the list
530 Modes.aircrafts = a;
531 }
532
533 if (mm->signalLevel > 0) {
534 a->signalLevel[a->signalNext] = mm->signalLevel;
535 a->signalNext = (a->signalNext + 1) & 7;
536 }
537 a->seen = now;
538 a->messages++;
539
540 // update addrtype, we only ever go towards "more direct" types
541 if (mm->addrtype < a->addrtype)
542 a->addrtype = mm->addrtype;
543
544 if (mm->altitude_valid && mm->altitude_source == ALTITUDE_BARO && accept_data(&a->altitude_valid, mm->source, now)) {
545 unsigned modeC = (a->altitude + 49) / 100;
546 if (modeC != a->altitude_modeC) {
547 a->modeCcount = 0; //....zero the hit count
548 a->modeACflags &= ~MODEAC_MSG_MODEC_HIT;
549 }
550
551 a->altitude = mm->altitude;
552 a->altitude_modeC = modeC;
553 }
554
555 if (mm->squawk_valid && accept_data(&a->squawk_valid, mm->source, now)) {
556 if (mm->squawk != a->squawk) {
557 a->modeAcount = 0; //....zero the hit count
558 a->modeACflags &= ~MODEAC_MSG_MODEA_HIT;
559 }
560 a->squawk = mm->squawk;
561 }
562
563 if (mm->altitude_valid && mm->altitude_source == ALTITUDE_GNSS && accept_data(&a->altitude_gnss_valid, mm->source, now)) {
564 a->altitude_gnss = mm->altitude;
565 }
566
567 if (mm->gnss_delta_valid && accept_data(&a->gnss_delta_valid, mm->source, now)) {
568 a->gnss_delta = mm->gnss_delta;
569 }
570
571 if (mm->heading_valid && mm->heading_source == HEADING_TRUE && accept_data(&a->heading_valid, mm->source, now)) {
572 a->heading = mm->heading;
573 }
574
575 if (mm->heading_valid && mm->heading_source == HEADING_MAGNETIC && accept_data(&a->heading_magnetic_valid, mm->source, now)) {
576 a->heading_magnetic = mm->heading;
577 }
578
579 if (mm->speed_valid && mm->speed_source == SPEED_GROUNDSPEED && accept_data(&a->speed_valid, mm->source, now)) {
580 a->speed = mm->speed;
581 }
582
583 if (mm->speed_valid && mm->speed_source == SPEED_IAS && accept_data(&a->speed_ias_valid, mm->source, now)) {
584 a->speed_ias = mm->speed;
585 }
586
587 if (mm->speed_valid && mm->speed_source == SPEED_TAS && accept_data(&a->speed_tas_valid, mm->source, now)) {
588 a->speed_tas = mm->speed;
589 }
590
591 if (mm->vert_rate_valid && accept_data(&a->vert_rate_valid, mm->source, now)) {
592 a->vert_rate = mm->vert_rate;
593 a->vert_rate_source = mm->vert_rate_source;
594 }
595
596 if (mm->category_valid && accept_data(&a->category_valid, mm->source, now)) {
597 a->category = mm->category;
598 }
599
600 if (mm->airground != AG_INVALID && accept_data(&a->airground_valid, mm->source, now)) {
601 a->airground = mm->airground;
602 }
603
604 if (mm->callsign_valid && accept_data(&a->callsign_valid, mm->source, now)) {
605 memcpy(a->callsign, mm->callsign, sizeof(a->callsign));
606 }
607
608 // CPR, even
609 if (mm->cpr_valid && !mm->cpr_odd && accept_data(&a->cpr_even_valid, mm->source, now)) {
610 a->cpr_even_type = mm->cpr_type;
611 a->cpr_even_lat = mm->cpr_lat;
612 a->cpr_even_lon = mm->cpr_lon;
613 a->cpr_even_nuc = mm->cpr_nucp;
614 }
615
616 // CPR, odd
617 if (mm->cpr_valid && mm->cpr_odd && accept_data(&a->cpr_odd_valid, mm->source, now)) {
618 a->cpr_odd_type = mm->cpr_type;
619 a->cpr_odd_lat = mm->cpr_lat;
620 a->cpr_odd_lon = mm->cpr_lon;
621 a->cpr_odd_nuc = mm->cpr_nucp;
622 }
623
624 // Now handle derived data
625
626 // derive GNSS if we have baro + delta
627 if (compare_validity(&a->altitude_valid, &a->altitude_gnss_valid, now) > 0 &&
628 compare_validity(&a->gnss_delta_valid, &a->altitude_gnss_valid, now) > 0) {
629 // Baro and delta are both more recent than GNSS, derive GNSS from baro + delta
630 a->altitude_gnss = a->altitude + a->gnss_delta;
631 combine_validity(&a->altitude_gnss_valid, &a->altitude_valid, &a->gnss_delta_valid);
632 }
633
634 // If we've got a new cprlat or cprlon
635 if (mm->cpr_valid) {
636 updatePosition(a, mm, now);
637 }
638
639 if (mm->msgtype == 32) {
640 int flags = a->modeACflags;
641 if ((flags & (MODEAC_MSG_MODEC_HIT | MODEAC_MSG_MODEC_OLD)) == MODEAC_MSG_MODEC_OLD) {
642 //
643 // This Mode-C doesn't currently hit any known Mode-S, but it used to because MODEAC_MSG_MODEC_OLD is
644 // set So the aircraft it used to match has either changed altitude, or gone out of our receiver range
645 //
646 // We've now received this Mode-A/C again, so it must be a new aircraft. It could be another aircraft
647 // at the same Mode-C altitude, or it could be a new airctraft with a new Mods-A squawk.
648 //
649 // To avoid masking this aircraft from the interactive display, clear the MODEAC_MSG_MODES_OLD flag
650 // and set messages to 1;
651 //
652 a->modeACflags = flags & ~MODEAC_MSG_MODEC_OLD;
653 a->messages = 1;
654 }
655 }
656
657 return (a);
658 }
659
660 //
661 // Periodic updates of tracking state
662 //
663
664 //
665 //=========================================================================
666 //
667 // Periodically search through the list of known Mode-S aircraft and tag them if this
668 // Mode A/C matches their known Mode S Squawks or Altitudes(+/- 50feet).
669 //
670 // A Mode S equipped aircraft may also respond to Mode A and Mode C SSR interrogations.
671 // We can't tell if this is a Mode A or C, so scan through the entire aircraft list
672 // looking for matches on Mode A (squawk) and Mode C (altitude). Flag in the Mode S
673 // records that we have had a potential Mode A or Mode C response from this aircraft.
674 //
675 // If an aircraft responds to Mode A then it's highly likely to be responding to mode C
676 // too, and vice verca. Therefore, once the mode S record is tagged with both a Mode A
677 // and a Mode C flag, we can be fairly confident that this Mode A/C frame relates to that
678 // Mode S aircraft.
679 //
680 // Mode C's are more likely to clash than Mode A's; There could be several aircraft
681 // cruising at FL370, but it's less likely (though not impossible) that there are two
682 // aircraft on the same squawk. Therefore, give precidence to Mode A record matches
683 //
684 // Note : It's theoretically possible for an aircraft to have the same value for Mode A
685 // and Mode C. Therefore we have to check BOTH A AND C for EVERY S.
686 //
687 static void trackUpdateAircraftModeA(struct aircraft *a)
688 {
689 struct aircraft *b = Modes.aircrafts;
690
691 while(b) {
692 if ((b->modeACflags & MODEAC_MSG_FLAG) == 0) { // skip any fudged ICAO records
693
694 // If both (a) and (b) have valid squawks...
695 if (trackDataValid(&a->squawk_valid) && trackDataValid(&b->squawk_valid)) {
696 // ...check for Mode-A == Mode-S Squawk matches
697 if (a->squawk == b->squawk) { // If a 'real' Mode-S ICAO exists using this Mode-A Squawk
698 b->modeAcount = a->messages;
699 b->modeACflags |= MODEAC_MSG_MODEA_HIT;
700 a->modeACflags |= MODEAC_MSG_MODEA_HIT;
701 if ( (b->modeAcount > 0) &&
702 ( (b->modeCcount > 1)
703 || (a->modeACflags & MODEAC_MSG_MODEA_ONLY)) ) // Allow Mode-A only matches if this Mode-A is invalid Mode-C
704 {a->modeACflags |= MODEAC_MSG_MODES_HIT;} // flag this ModeA/C probably belongs to a known Mode S
705 }
706 }
707
708 // If both (a) and (b) have valid altitudes...
709 if (trackDataValid(&a->altitude_valid) && trackDataValid(&b->altitude_valid)) {
710 // ... check for Mode-C == Mode-S Altitude matches
711 if ( (a->altitude_modeC == b->altitude_modeC ) // If a 'real' Mode-S ICAO exists at this Mode-C Altitude
712 || (a->altitude_modeC == b->altitude_modeC + 1) // or this Mode-C - 100 ft
713 || (a->altitude_modeC + 1 == b->altitude_modeC ) ) { // or this Mode-C + 100 ft
714 b->modeCcount = a->messages;
715 b->modeACflags |= MODEAC_MSG_MODEC_HIT;
716 a->modeACflags |= MODEAC_MSG_MODEC_HIT;
717 if ( (b->modeAcount > 0) &&
718 (b->modeCcount > 1) )
719 {a->modeACflags |= (MODEAC_MSG_MODES_HIT | MODEAC_MSG_MODEC_OLD);} // flag this ModeA/C probably belongs to a known Mode S
720 }
721 }
722 }
723 b = b->next;
724 }
725 }
726 //
727 //=========================================================================
728 //
729 static void trackUpdateAircraftModeS()
730 {
731 struct aircraft *a = Modes.aircrafts;
732
733 while(a) {
734 int flags = a->modeACflags;
735 if (flags & MODEAC_MSG_FLAG) { // find any fudged ICAO records
736
737 // clear the current A,C and S hit bits ready for this attempt
738 a->modeACflags = flags & ~(MODEAC_MSG_MODEA_HIT | MODEAC_MSG_MODEC_HIT | MODEAC_MSG_MODES_HIT);
739
740 trackUpdateAircraftModeA(a); // and attempt to match them with Mode-S
741 }
742 a = a->next;
743 }
744 }
745
746 //
747 //=========================================================================
748 //
749 // If we don't receive new nessages within TRACK_AIRCRAFT_TTL
750 // we remove the aircraft from the list.
751 //
752 static void trackRemoveStaleAircraft(uint64_t now)
753 {
754 struct aircraft *a = Modes.aircrafts;
755 struct aircraft *prev = NULL;
756
757 while(a) {
758 if ((now - a->seen) > TRACK_AIRCRAFT_TTL ||
759 (a->messages == 1 && (now - a->seen) > TRACK_AIRCRAFT_ONEHIT_TTL)) {
760 // Count aircraft where we saw only one message before reaping them.
761 // These are likely to be due to messages with bad addresses.
762 if (a->messages == 1)
763 Modes.stats_current.single_message_aircraft++;
764
765 // Remove the element from the linked list, with care
766 // if we are removing the first element
767 if (!prev) {
768 Modes.aircrafts = a->next; free(a); a = Modes.aircrafts;
769 } else {
770 prev->next = a->next; free(a); a = prev->next;
771 }
772 } else {
773
774 #define EXPIRE(_f) do { if (a->_f##_valid.source != SOURCE_INVALID && now >= a->_f##_valid.expires) { a->_f##_valid.source = SOURCE_INVALID; } } while (0)
775 EXPIRE(callsign);
776 EXPIRE(altitude);
777 EXPIRE(altitude_gnss);
778 EXPIRE(gnss_delta);
779 EXPIRE(speed);
780 EXPIRE(speed_ias);
781 EXPIRE(speed_tas);
782 EXPIRE(heading);
783 EXPIRE(heading_magnetic);
784 EXPIRE(vert_rate);
785 EXPIRE(squawk);
786 EXPIRE(category);
787 EXPIRE(airground);
788 EXPIRE(cpr_odd);
789 EXPIRE(cpr_even);
790 EXPIRE(position);
791
792 prev = a; a = a->next;
793 }
794 }
795 }
796
797
798 //
799 // Entry point for periodic updates
800 //
801
802 void trackPeriodicUpdate()
803 {
804 static uint64_t next_update;
805 uint64_t now = mstime();
806
807 // Only do updates once per second
808 if (now >= next_update) {
809 next_update = now + 1000;
810 trackRemoveStaleAircraft(now);
811 trackUpdateAircraftModeS();
812 }
813 }