// SPDX-FileCopyrightText: © 2012 Salvatore Sanfilippo // SPDX-FileCopyrightText: © 2014-2016 Oliver Jowett // SPDX-FileCopyrightText: © 2021 FlightAware LLC // SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: GPL-2.0-or-later //! Assembling a picture of each aircraft out of the fragments its messages //! carry. //! //! No Mode S message describes an aircraft. One carries an altitude, another //! half a position, another a callsign, and each arrives from a source of //! different trustworthiness — an extended squitter whose CRC checked out, a //! Comm-B reply whose register had to be guessed at, a multilateration result //! computed by somebody else. The tracker's job is to hold the current state //! of each aircraft and decide, field by field, which arriving fragment //! should be allowed to change it. //! //! Two mechanisms do that work. //! //! **Every field ages.** A tracked value passes through three states: *fresh*, //! where only an equally good or better source may replace it; *stale*, where //! anything may; and *expired*, where it is gone. That is what stops one //! good ADS-B report from pinning a field against every later Mode S update, //! and what stops a value from outliving the aircraft's presence. //! //! **Positions are checked against physics.** CPR is ambiguous by //! construction, and a wrong resolution does not fail — it produces a //! confident position hundreds of miles away. So every solved position is //! checked against how far the aircraft could actually have travelled since //! the last one, and against the receiver's range. A position that fails is //! not merely dropped: the CPR pair that produced it is thrown away too, on //! the grounds that one of the two messages was corrupt. const std = @import("std"); const Allocator = std.mem.Allocator; const cpr = @import("cpr.zig"); const geo = @import("geo"); const message = @import("message.zig"); const mode_ac = @import("mode_ac.zig"); const Message = message.Message; const Source = message.Source; /// Metres in a nautical mile. const meters_per_nautical_mile = 1852.0; /// How long an aircraft we believe in survives without being heard from. pub const aircraft_ttl_ms = 300_000; /// How long an aircraft we do not yet believe in survives. Short, because /// most of them are noise that produced one plausible-looking address. pub const unreliable_aircraft_ttl_ms = 60_000; /// How many Mode A/C replies with the same code must arrive in a second /// before the code is believed to be a real aircraft's. pub const modeac_min_messages = 4; /// How many clean DF17s make a track believable on their own. pub const reliable_df17_messages = 2; /// How many clean DF11s do. pub const reliable_df11_messages = 3; /// How many messages of any kind do. pub const reliable_any_messages = 5; /// The radius-of-containment value meaning "not known". Zero is not a /// possible real radius, so it can serve as the sentinel. pub const rc_unknown: u32 = 0; /// Buckets in the range histogram. pub const range_bucket_count = 76; /// Where a tracked value came from and when it goes off. /// /// Kept separate from `Tracked` so that two differently-typed fields can have /// their validities combined — which is what deriving a geometric altitude /// from a barometric one plus a delta requires. pub const Validity = struct { source: Source = .invalid, /// When the value last arrived. updated: u64 = 0, /// When a worse source is allowed to replace it. stale: u64 = 0, /// When it stops being a value at all. expires: u64 = 0, pub const invalid: Validity = .{}; /// Whether the value may still be used. pub fn isValid(self: Validity, now: u64) bool { return self.source != .invalid and now < self.expires; } /// Whether the value is still fresh enough to fend off a worse source. pub fn isFresh(self: Validity, now: u64) bool { return self.source != .invalid and now < self.stale; } /// How long ago the value arrived, in milliseconds. A value that was /// never set is infinitely old. pub fn age(self: Validity, now: u64) u64 { if (self.source == .invalid) return std.math.maxInt(u64); if (self.updated >= now) return 0; return now - self.updated; } /// The validity of something derived from two other values: no better /// than the worse source, no fresher than the earlier deadline, and as /// recent as the later update. pub fn combine(a: Validity, b: Validity) Validity { if (a.source == .invalid) return b; if (b.source == .invalid) return a; return .{ .source = @enumFromInt(@min(@intFromEnum(a.source), @intFromEnum(b.source))), .updated = @max(a.updated, b.updated), .stale = @min(a.stale, b.stale), .expires = @min(a.expires, b.expires), }; } /// Which of two values should be preferred: the one from the better /// source while that one is still fresh, and otherwise the more recent. pub fn compare(self: Validity, other: Validity, now: u64) std.math.Order { if (now < self.stale and @intFromEnum(self.source) > @intFromEnum(other.source)) return .gt; if (now < other.stale and @intFromEnum(self.source) < @intFromEnum(other.source)) return .lt; return std.math.order(self.updated, other.updated); } }; /// One tracked field: a value, where it came from, and how long each of its /// three states lasts. /// /// The intervals are compile-time parameters rather than stored fields, so a /// declaration reads as the table upstream keeps in its constructor — /// `Tracked(i32, 15, 70)` is a value that goes stale after fifteen seconds /// and expires after seventy. pub fn Tracked(comptime T: type, comptime stale_seconds: u64, comptime expire_seconds: u64) type { return struct { const Self = @This(); /// Marker so that `Aircraft` can find its tracked fields /// reflectively and expire them all. pub const is_tracked = {}; pub const stale_interval = stale_seconds * 1000; pub const expire_interval = expire_seconds * 1000; value: T = std.mem.zeroes(T), validity: Validity = .invalid, pub const init: Self = .{}; pub fn isValid(self: Self, now: u64) bool { return self.validity.isValid(now); } pub fn isFresh(self: Self, now: u64) bool { return self.validity.isFresh(now); } pub fn age(self: Self, now: u64) u64 { return self.validity.age(now); } /// The value, if it is still usable. pub fn get(self: Self, now: u64) ?T { return if (self.isValid(now)) self.value else null; } /// Whether an update from `source` should be taken, and if so, mark /// the field as freshly updated. /// /// A worse source is refused while the current value is still fresh, /// and any source is refused if the message somehow predates what is /// already recorded. pub fn accept(self: *Self, now: u64, source: Source) bool { if (now < self.validity.updated) return false; if (@intFromEnum(source) < @intFromEnum(self.validity.source) and now < self.validity.stale) return false; self.validity = .{ .source = source, .updated = now, .stale = now + stale_interval, .expires = now + expire_interval, }; return true; } /// Accept an update and store it, or leave the field alone. Returns /// whether the update was taken. pub fn set(self: *Self, now: u64, source: Source, value: T) bool { if (!self.accept(now, source)) return false; self.value = value; return true; } /// Drop the value if its time is up. pub fn expire(self: *Self, now: u64) void { if (self.validity.source != .invalid and now >= self.validity.expires) self.validity.source = .invalid; } }; } /// Half of a CPR position pair: one message's worth, waiting for its /// opposite. pub const CprHalf = struct { type: message.CprType = .surface, encoded: cpr.Encoded = .{ .latitude = 0, .longitude = 0 }, /// Navigation Integrity Category implied by the message type. nic: u8 = 0, /// Radius of containment in metres, or `rc_unknown`. rc: u32 = 0, }; /// A resolved position and what the resolution says about its precision. pub const FixedPosition = struct { position: cpr.Position = .{ .latitude = 0, .longitude = 0 }, nic: u8 = 0, rc: u32 = 0, }; /// The last values the FATSV output reported for an aircraft. /// /// FATSV is a change feed rather than a message feed: most fields are sent /// only when they have moved far enough to be worth saying, so the emitter /// has to remember what it last said. Kept as its own struct rather than as /// three dozen fields on `Aircraft`, because it is one concern and nothing /// outside `fatsv.zig` reads it. /// /// The defaults are upstream's assumptions for an aircraft nothing has been /// heard from yet: ADS-B over an ICAO address, version zero, category A0. pub const Fatsv = struct { altitude_baro: i32 = 0, altitude_geom: i32 = 0, baro_rate: i32 = 0, geom_rate: i32 = 0, track: f32 = 0, track_rate: f32 = 0, mag_heading: f32 = 0, true_heading: f32 = 0, roll: f32 = 0, gs: f32 = 0, ias: u32 = 0, tas: u32 = 0, mach: f64 = 0, airground: message.AirGround = .invalid, nav_altitude_mcp: i32 = 0, nav_altitude_fms: i32 = 0, nav_altitude_src: message.NavAltitudeSource = .invalid, nav_heading: f32 = 0, nav_modes: message.NavModes = .{}, nav_qnh: f32 = 0, callsign: [8]u8 = @splat(0), /// Unknown rather than the usual type, so that the first line always /// states what kind of address this is. address_type: message.AddressType = .unknown, adsb_version: ?u3 = null, category: u8 = 0, squawk: u16 = 0, nac_p: u4 = 0, nac_v: u3 = 0, sil: u2 = 0, sil_type: message.SilType = .invalid, nic_baro: u1 = 0, emergency: message.Emergency = .none, /// The seven-byte payloads of the event records, which are sent whenever /// they differ from the last one seen. /// /// The two resolution-advisory reports start as an empty one — the /// register code alone — so that an aircraft with nothing to advise is /// not reported as having changed its mind. bds_10: [7]u8 = @splat(0), bds_17: [7]u8 = @splat(0), bds_30: [7]u8 = .{ 0x30, 0, 0, 0, 0, 0, 0 }, unknown_commb: [7]u8 = @splat(0), es_status: [7]u8 = @splat(0), es_acas_ra: [7]u8 = .{ 0xe2, 0, 0, 0, 0, 0, 0 }, /// When this aircraft was last reported at all, and when the /// only-on-change fields were last sent regardless of whether they had. last_emitted: u64 = 0, last_force_emit: u64 = 0, }; /// Everything known about one aircraft. pub const Aircraft = struct { /// The ICAO address, with `message.non_icao_address` set if it is not /// really one. address: u32, /// The most direct address type seen. Only ever revised towards more /// direct, never away. address_type: message.AddressType, /// When the last message arrived. seen: u64 = 0, /// How many messages have been received. messages: u64 = 0, /// Whether this is believed to be a real aircraft rather than noise that /// happened to decode. reliable: bool = false, /// Clean DF11s received: no corrections, interrogator identity zero. reliable_df11: u64 = 0, /// Clean DF17s received: no corrections. reliable_df17: u64 = 0, /// Messages thrown away because neither they nor the track were trusted. discarded: u64 = 0, /// The last eight signal levels, as a ring buffer, for the average the /// JSON output reports. signal_level: [8]f64 = @splat(1e-5), signal_next: u3 = 0, callsign: Tracked([8]u8, 60, 70) = .init, altitude_baro: Tracked(i32, 15, 70) = .init, altitude_geom: Tracked(i32, 60, 70) = .init, geom_delta: Tracked(i32, 60, 70) = .init, gs: Tracked(f32, 60, 70) = .init, ias: Tracked(u32, 60, 70) = .init, tas: Tracked(u32, 60, 70) = .init, mach: Tracked(f64, 60, 70) = .init, track: Tracked(f32, 60, 70) = .init, track_rate: Tracked(f32, 60, 70) = .init, roll: Tracked(f32, 60, 70) = .init, mag_heading: Tracked(f32, 60, 70) = .init, true_heading: Tracked(f32, 60, 70) = .init, baro_rate: Tracked(i32, 60, 70) = .init, geom_rate: Tracked(i32, 60, 70) = .init, squawk: Tracked(u16, 15, 70) = .init, emergency: Tracked(message.Emergency, 60, 70) = .init, airground: Tracked(message.AirGround, 15, 70) = .init, nav_qnh: Tracked(f32, 60, 70) = .init, nav_altitude_mcp: Tracked(i32, 60, 70) = .init, nav_altitude_fms: Tracked(i32, 60, 70) = .init, nav_altitude_src: Tracked(message.NavAltitudeSource, 60, 70) = .init, nav_heading: Tracked(f32, 60, 70) = .init, nav_modes: Tracked(message.NavModes, 60, 70) = .init, cpr_even: Tracked(CprHalf, 60, 70) = .init, cpr_odd: Tracked(CprHalf, 60, 70) = .init, position: Tracked(FixedPosition, 60, 70) = .init, nic_a: Tracked(u1, 60, 70) = .init, nic_c: Tracked(u1, 60, 70) = .init, nic_baro: Tracked(u1, 60, 70) = .init, nac_p: Tracked(u4, 60, 70) = .init, nac_v: Tracked(u3, 60, 70) = .init, sil: Tracked(u2, 60, 70) = .init, gva: Tracked(u2, 60, 70) = .init, sda: Tracked(u2, 60, 70) = .init, mrar_source: Tracked(message.MrarSource, 60, 70) = .init, wind: Tracked(struct { speed: f32, direction: f32 }, 60, 70) = .init, temperature: Tracked(f32, 60, 70) = .init, pressure: Tracked(f32, 60, 70) = .init, turbulence: Tracked(message.Hazard, 60, 70) = .init, humidity: Tracked(f32, 60, 70) = .init, /// The wake turbulence and emitter category, A0 to D7 as one hex byte, or /// null if never reported. Categories do not change, so this is not /// tracked with a validity. category: ?u8 = null, /// How the SIL should be read. Kept beside `sil` rather than in it, /// because a message may revise one without the other. sil_type: message.SilType = .invalid, /// The ADS-B version this aircraft implements, or null if no ADS-B /// message has been seen. Where a version is needed and none is known, /// version 0 is assumed. adsb_version: ?u3 = null, /// The same for ADS-R rebroadcasts of this aircraft. adsr_version: ?u3 = null, /// The same for TIS-B reports of it. tisb_version: ?u3 = null, /// Which north this aircraft's headings are referenced to. adsb_hrd: message.HeadingType = .magnetic_heading, /// Whether its surface movement reports give track or heading. adsb_tah: message.HeadingType = .ground_track, /// What the FATSV output last said about this aircraft, so that it can /// send changes rather than a full report every time. fatsv: Fatsv = .{}, /// The earliest this aircraft may next appear on a reduced Beast feed. reduce_next_forward_ms: u64 = 0, /// Whether a Mode A/C reply matching this aircraft's squawk was heard in /// the last check period. mode_a_hit: bool = false, /// Whether one matching its altitude was. mode_c_hit: bool = false, /// Whether the address is a real ICAO one rather than an anonymous or /// track-file identifier. pub fn addressIsIcao(self: *const Aircraft) bool { return self.address & message.non_icao_address == 0; } /// The mean of the last eight signal levels, as a power fraction. pub fn meanSignalLevel(self: *const Aircraft) f64 { var total: f64 = 0; for (self.signal_level) |level| total += level; return total / self.signal_level.len; } /// Drop every tracked field whose time is up. fn expireAll(self: *Aircraft, now: u64) void { inline for (@typeInfo(Aircraft).@"struct".fields) |field| { if (@typeInfo(field.type) == .@"struct" and @hasDecl(field.type, "is_tracked")) { @field(self, field.name).expire(now); } } } }; /// What the receiver knows about itself, which is what makes a surface /// position or a relative decode possible at all. pub const Receiver = struct { /// Where the antenna is, if the user said. position: ?cpr.Position = null, /// The furthest away an aircraft can plausibly be, in metres. Zero /// disables the range checks — and with them the receiver-relative /// position decode, which has no way to resolve its ambiguity without a /// bound on the range. /// /// Three hundred nautical miles is upstream's default: about the radio /// horizon for an aircraft at cruise, and comfortably inside the half /// cell that would make a relative decode ambiguous. max_range: f64 = 1852 * 300, /// Whether to accumulate the range histogram. range_histogram: bool = false, }; /// Counters the tracker accumulates, for the statistics output. pub const Counters = struct { unique_aircraft: u64 = 0, single_message_aircraft: u64 = 0, unreliable_aircraft: u64 = 0, cpr_surface: u64 = 0, cpr_airborne: u64 = 0, cpr_global_ok: u64 = 0, cpr_global_bad: u64 = 0, cpr_global_skipped: u64 = 0, cpr_global_range_checks: u64 = 0, cpr_global_speed_checks: u64 = 0, cpr_local_ok: u64 = 0, cpr_local_skipped: u64 = 0, cpr_local_range_checks: u64 = 0, cpr_local_speed_checks: u64 = 0, range_histogram: [range_bucket_count]u32 = @splat(0), }; /// Why a position could not be established. const PositionError = error{ /// Nothing was wrong with the data; there was just no way to resolve it /// this time. Try again when the next message arrives. Skipped, /// The data was bad: it resolved to somewhere the aircraft cannot be. /// The messages that produced it should be discarded. Rejected, }; /// The Mode A/C side of tracking, which is kept separately. /// /// A Mode A/C reply has no address, so there is nothing to track *per* /// aircraft — only a count of how often each of the 4096 codes has been heard, /// and an attempt to match those codes against the squawks and altitudes of /// aircraft that are being tracked properly. const ModeAcTable = struct { /// How many replies with each code have been heard, ever. count: [4096]u32 = @splat(0), /// What `count` was at the last check, so the rate can be worked out. last_count: [4096]u32 = @splat(0), /// The address of the aircraft a code was matched to, or 0xffffffff if /// more than one matched and the code is therefore ambiguous. match: [4096]u32 = @splat(0), /// How many check periods a code has gone without enough replies. age: [4096]u32 = @splat(0), const ambiguous: u32 = 0xffff_ffff; /// Whether this code has been heard often enough since the last check to /// be a real aircraft rather than a stray decode. fn isLive(self: *const ModeAcTable, index: u12) bool { return self.count[index] - self.last_count[index] >= modeac_min_messages; } fn recordMatch(self: *ModeAcTable, index: u12, address: u32) void { self.match[index] = if (self.match[index] != 0) ambiguous else address; } }; /// The set of aircraft currently being tracked. pub const Tracker = struct { gpa: Allocator, receiver: Receiver, counters: Counters = .{}, /// The tracked aircraft, keyed by address. /// /// An array hash map rather than a plain one because iteration order is /// observable: it is the order aircraft appear in the JSON output. It is /// walked backwards, since upstream keeps a list and pushes new aircraft /// onto the front of it. aircraft: std.AutoArrayHashMapUnmanaged(u32, *Aircraft) = .empty, mode_ac: ModeAcTable = .{}, /// When the once-a-second housekeeping is next due. next_periodic_ms: u64 = 0, pub fn init(gpa: Allocator, receiver: Receiver) Tracker { return .{ .gpa = gpa, .receiver = receiver }; } pub fn deinit(self: *Tracker) void { for (self.aircraft.values()) |aircraft| self.gpa.destroy(aircraft); self.aircraft.deinit(self.gpa); self.* = undefined; } /// Iterate the tracked aircraft in the order the outputs present them: /// most recently first seen first. pub fn iterator(self: *const Tracker) Iterator { return .{ .values = self.aircraft.values(), .index = self.aircraft.count() }; } pub const Iterator = struct { values: []const *Aircraft, index: usize, pub fn next(self: *Iterator) ?*Aircraft { if (self.index == 0) return null; self.index -= 1; return self.values[self.index]; } }; /// Look up an aircraft by address. pub fn find(self: *const Tracker, address: u32) ?*Aircraft { return self.aircraft.get(address); } /// Update the tracked state from a message, and return the aircraft it /// belongs to. /// /// Returns null for a message that names no aircraft: a Mode A/C reply, /// which is counted separately, or one whose address decoded as zero. /// /// `mm` is taken by pointer because the tracker writes back into it — /// the resolved position, the ground speed reading that the aircraft's /// ADS-B version selects, and the accuracy figures that a version 0 /// message implies rather than states. Those are what the output formats /// print, and they are not knowable from the message alone. pub fn update(self: *Tracker, mm: *Message) Allocator.Error!?*Aircraft { if (mm.format == .mode_ac) { // No address, so nothing to track: just count the code. The ident // bit is not part of it. if (mm.squawk) |squawk| self.mode_ac.count[mode_ac.toIndex(squawk)] += 1; return null; } // A zero address is not an aircraft, it is a decode that went wrong. if (mm.address == 0) return null; const now = mm.system_timestamp_ms; const aircraft = try self.findOrCreate(mm); if (mm.signal_level > 0) { aircraft.signal_level[aircraft.signal_next] = mm.signal_level; aircraft.signal_next +%= 1; } aircraft.seen = now; aircraft.messages += 1; // Decide whether this is a real aircraft. Noise produces plausible // addresses constantly; what it does not produce is a stream of them. if (mm.reliable) { if (mm.format.is(11)) aircraft.reliable_df11 += 1; if (mm.format.is(17)) aircraft.reliable_df17 += 1; } if (aircraft.reliable_df11 >= reliable_df11_messages or aircraft.reliable_df17 >= reliable_df17_messages or aircraft.messages >= reliable_any_messages) { aircraft.reliable = true; } // An untrusted message about an untrusted track tells us nothing. if (!mm.reliable and !aircraft.reliable) { aircraft.discarded += 1; return aircraft; } // Address types only ever improve. if (@intFromEnum(mm.address_type) < @intFromEnum(aircraft.address_type)) aircraft.address_type = mm.address_type; self.applyVersionAndAccuracy(aircraft, mm); self.applyFields(aircraft, mm, now); try self.applyPosition(aircraft, mm, now); return aircraft; } fn findOrCreate(self: *Tracker, mm: *const Message) Allocator.Error!*Aircraft { const entry = try self.aircraft.getOrPut(self.gpa, mm.address); if (entry.found_existing) return entry.value_ptr.*; errdefer _ = self.aircraft.orderedRemove(mm.address); const aircraft = try self.gpa.create(Aircraft); aircraft.* = .{ .address = mm.address, .address_type = mm.address_type, // Both FATSV clocks start now rather than at zero, so that a new // aircraft waits its turn like any other and its first line is a // change report rather than a full one. .fatsv = .{ .last_emitted = mm.system_timestamp_ms, .last_force_emit = mm.system_timestamp_ms, }, }; entry.value_ptr.* = aircraft; self.counters.unique_aircraft += 1; return aircraft; } /// Work out which ADS-B version applies, and fill in the accuracy figures /// that a version 0 message implies but does not state. fn applyVersionAndAccuracy(self: *Tracker, aircraft: *Aircraft, mm: *Message) void { _ = self; // Which version field this message revises depends on who sent it: an // ADS-R rebroadcast says nothing about the aircraft's own equipment. const version_field: *?u3 = switch (mm.source) { .adsb => &aircraft.adsb_version, .tisb => &aircraft.tisb_version, .adsr => &aircraft.adsr_version, else => null, } orelse blk: { // Anything else revises nothing; give it somewhere harmless to // write. var scratch: ?u3 = null; break :blk &scratch; }; // Assume version 0 until told otherwise, which is what the standard // says to do. if (version_field.* == null) version_field.* = 0; if (mm.category) |category| aircraft.category = category; // The operational status message is read first, because it is what // says how to read everything else. if (mm.opstatus) |status| { version_field.* = status.version; if (status.hrd != .invalid) aircraft.adsb_hrd = status.hrd; if (status.tah != .invalid) aircraft.adsb_tah = status.tah; } const version = version_field.*.?; // A version 0 aircraft does not report NACp or SIL at all; the // position message type implies them. ED-102A tables N-7 and N-8. if (version == 0 and mm.accuracy.nac_p == null) { if (version0Nacp(mm)) |nac_p| mm.accuracy.nac_p = nac_p; } if (version == 0 and mm.accuracy.sil_type == .invalid) { if (version0Sil(mm)) |sil| { mm.accuracy.sil_type = .unknown; mm.accuracy.sil = sil; } } } /// Take whatever the message says about each field, subject to the /// source ranking. fn applyFields(self: *Tracker, aircraft: *Aircraft, mm: *Message, now: u64) void { _ = self; if (mm.altitude_baro) |altitude| { if (aircraft.altitude_baro.accept(now, mm.source)) { const feet = altitudeToFeet(altitude); // A Mode A/C reply that matched this aircraft's altitude no // longer matches if the altitude has moved. if (aircraft.mode_c_hit) { if (hundredsOfFeet(aircraft.altitude_baro.value) != hundredsOfFeet(feet)) aircraft.mode_c_hit = false; } aircraft.altitude_baro.value = feet; } } if (mm.squawk) |squawk| { if (aircraft.squawk.accept(now, mm.source)) { if (squawk != aircraft.squawk.value) aircraft.mode_a_hit = false; aircraft.squawk.value = squawk; } } if (mm.emergency) |emergency| _ = aircraft.emergency.set(now, mm.source, emergency); if (mm.altitude_geom) |altitude| _ = aircraft.altitude_geom.set(now, mm.source, altitudeToFeet(altitude)); if (mm.geom_delta) |delta| _ = aircraft.geom_delta.set(now, mm.source, delta); if (mm.heading) |heading| { // Two of the heading types are not answers but references to the // aircraft's own operational status, which the tracker knows and // the decoder did not. const kind = switch (heading.type) { .magnetic_or_true => aircraft.adsb_hrd, .track_or_heading => aircraft.adsb_tah, else => heading.type, }; switch (kind) { .ground_track => _ = aircraft.track.set(now, mm.source, heading.degrees), .magnetic_heading => _ = aircraft.mag_heading.set(now, mm.source, heading.degrees), .true_heading => _ = aircraft.true_heading.set(now, mm.source, heading.degrees), else => {}, } } if (mm.track_rate) |rate| _ = aircraft.track_rate.set(now, mm.source, rate); if (mm.roll) |roll| _ = aircraft.roll.set(now, mm.source, roll); if (mm.gs) |*speed| { // A surface movement report means different speeds in ADS-B // version 0 and version 2, and the message does not say which it // is. Now that the version is known, choose — and write the // choice back, since that is what the outputs print. const version = aircraft.adsb_version orelse 0; speed.selected = if (version == 2) speed.v2 else speed.v0; _ = aircraft.gs.set(now, mm.source, speed.selected); } if (mm.ias) |ias| _ = aircraft.ias.set(now, mm.source, ias); if (mm.tas) |tas| _ = aircraft.tas.set(now, mm.source, tas); if (mm.mach) |mach| _ = aircraft.mach.set(now, mm.source, mach); if (mm.baro_rate) |rate| _ = aircraft.baro_rate.set(now, mm.source, rate); if (mm.geom_rate) |rate| _ = aircraft.geom_rate.set(now, mm.source, rate); if (mm.airground != .invalid) { // An uncertain report is not allowed to overwrite a certain one // while the certain one is still fresh. if (mm.airground != .uncertain or !aircraft.airground.isFresh(now)) _ = aircraft.airground.set(now, mm.source, mm.airground); } if (mm.callsign) |callsign| _ = aircraft.callsign.set(now, mm.source, callsign); if (mm.nav.mcp_altitude) |altitude| _ = aircraft.nav_altitude_mcp.set(now, mm.source, altitude); if (mm.nav.fms_altitude) |altitude| _ = aircraft.nav_altitude_fms.set(now, mm.source, altitude); if (mm.nav.altitude_source != .invalid) _ = aircraft.nav_altitude_src.set(now, mm.source, mm.nav.altitude_source); if (mm.nav.heading) |heading| _ = aircraft.nav_heading.set(now, mm.source, heading.degrees); if (mm.nav.modes) |engaged| _ = aircraft.nav_modes.set(now, mm.source, engaged); if (mm.nav.qnh) |qnh| _ = aircraft.nav_qnh.set(now, mm.source, qnh); // Upstream applies SDA twice, once here and once after GVA. The // second application is idempotent, so it is not reproduced. if (mm.accuracy.nic_a) |value| _ = aircraft.nic_a.set(now, mm.source, value); if (mm.accuracy.nic_c) |value| _ = aircraft.nic_c.set(now, mm.source, value); if (mm.accuracy.nic_baro) |value| _ = aircraft.nic_baro.set(now, mm.source, value); if (mm.accuracy.nac_p) |value| _ = aircraft.nac_p.set(now, mm.source, value); if (mm.accuracy.nac_v) |value| _ = aircraft.nac_v.set(now, mm.source, value); if (mm.accuracy.gva) |value| _ = aircraft.gva.set(now, mm.source, value); if (mm.accuracy.sda) |value| _ = aircraft.sda.set(now, mm.source, value); if (mm.accuracy.sil_type != .invalid) { if (aircraft.sil.set(now, mm.source, mm.accuracy.sil)) { // A message that says only "there is a SIL" does not // overwrite one that said what the SIL is per. if (aircraft.sil_type == .invalid or mm.accuracy.sil_type != .unknown) aircraft.sil_type = mm.accuracy.sil_type; } } const met = mm.meteorology; if (met.source) |source| _ = aircraft.mrar_source.set(now, mm.source, source); if (met.wind) |wind| _ = aircraft.wind.set(now, mm.source, .{ .speed = wind.speed, .direction = wind.direction }); if (met.temperature) |value| _ = aircraft.temperature.set(now, mm.source, value); if (met.pressure) |value| _ = aircraft.pressure.set(now, mm.source, value); if (met.turbulence) |value| _ = aircraft.turbulence.set(now, mm.source, value); if (met.humidity) |value| _ = aircraft.humidity.set(now, mm.source, value); // A geometric altitude can be had without a message carrying one, if // a barometric altitude and the difference between the two are both // more recent than the last geometric altitude heard. if (aircraft.altitude_baro.validity.compare(aircraft.altitude_geom.validity, now) == .gt and aircraft.geom_delta.validity.compare(aircraft.altitude_geom.validity, now) == .gt) { aircraft.altitude_geom.value = aircraft.altitude_baro.value + aircraft.geom_delta.value; aircraft.altitude_geom.validity = .combine(aircraft.altitude_baro.validity, aircraft.geom_delta.validity); } } /// Store this message's half of a CPR pair, and try to resolve a position /// if it completed one. fn applyPosition(self: *Tracker, aircraft: *Aircraft, mm: *Message, now: u64) Allocator.Error!void { const reported = mm.cpr orelse return; const half: CprHalf = blk: { const accuracy = self.computeNicRc(aircraft, mm, now); break :blk .{ .type = reported.type, .encoded = reported.encoded, .nic = accuracy.nic, .rc = accuracy.rc, }; }; const stored = switch (reported.frame) { .even => aircraft.cpr_even.set(now, mm.source, half), .odd => aircraft.cpr_odd.set(now, mm.source, half), }; if (!stored) return; self.updatePosition(aircraft, mm, now); } fn updatePosition(self: *Tracker, aircraft: *Aircraft, mm: *Message, now: u64) void { const reported = mm.cpr.?; const surface = reported.type == .surface; // How far apart the two halves of a pair may be and still describe // the same place. An aircraft crossing a CPR zone between the two // messages would otherwise resolve to somewhere it is not. const max_elapsed: u64 = if (surface) blk: { self.counters.cpr_surface += 1; // A stationary aircraft on the ground can afford a longer window. const slow = if (mm.gs) |speed| speed.selected <= 25 else false; break :blk if (slow) 50_000 else 25_000; } else blk: { self.counters.cpr_airborne += 1; break :blk 10_000; }; var fixed: ?FixedPosition = null; var relative = false; // A pair of opposite-parity messages resolves a position outright, // if both are recent enough and came from the same kind of source. const pair_usable = aircraft.cpr_even.isValid(now) and aircraft.cpr_odd.isValid(now) and aircraft.cpr_even.validity.source == aircraft.cpr_odd.validity.source and aircraft.cpr_even.value.type == aircraft.cpr_odd.value.type and timeBetween(aircraft.cpr_even.validity.updated, aircraft.cpr_odd.validity.updated) <= max_elapsed; var rejected = false; if (pair_usable) { if (self.globalPosition(aircraft, mm, now)) |solved| { if (aircraft.position.accept(now, mm.source)) { self.counters.cpr_global_ok += 1; fixed = solved; } else { self.counters.cpr_global_skipped += 1; rejected = true; } } else |err| switch (err) { error.Skipped => self.counters.cpr_global_skipped += 1, error.Rejected => { // The pair resolved to somewhere the aircraft cannot be, // so one of the two messages was wrong. Throw both away // and wait for a fresh pair, and stop trusting the last // position enough to decode relative to it. self.counters.cpr_global_bad += 1; aircraft.cpr_even.validity.source = .invalid; aircraft.cpr_odd.validity.source = .invalid; aircraft.position.validity.source = .invalid; return; }, } } // Otherwise fall back to resolving against a known reference. if (fixed == null and !rejected) { if (self.localPosition(aircraft, mm, now)) |solved| { if (aircraft.position.accept(now, mm.source)) { self.counters.cpr_local_ok += 1; fixed = solved; relative = true; } else { self.counters.cpr_local_skipped += 1; } } else |_| { self.counters.cpr_local_skipped += 1; } } const solved = fixed orelse return; // Write the answer back into the message, since that is what the // outputs print, and into the aircraft, since that is what the next // relative decode will use as its reference. mm.decoded_position = .{ .position = solved.position, .nic = solved.nic, .rc = solved.rc, .relative = relative, }; aircraft.position.value = solved; self.recordRange(solved.position); } /// Resolve a position from the two halves of a CPR pair, needing no prior /// knowledge of where the aircraft is. fn globalPosition(self: *Tracker, aircraft: *Aircraft, mm: *const Message, now: u64) PositionError!FixedPosition { const reported = mm.cpr.?; const even = aircraft.cpr_even.value; const odd = aircraft.cpr_odd.value; // The accuracy of a combined position is the worse of the two. const nic = @min(even.nic, odd.nic); const rc = if (rcIsWorse(even.rc, odd.rc)) even.rc else odd.rc; const position = switch (reported.type) { .surface => blk: { // The surface grid covers a quarter of the globe, so even a // global solve needs a reference to pick a quadrant: where // the aircraft was last seen, or failing that the receiver. const reference = if (aircraft.position.isValid(now)) aircraft.position.value.position else self.receiver.position orelse return error.Skipped; break :blk cpr.decodeGlobalSurface(reference, even.encoded, odd.encoded, reported.frame) catch |err| switch (err) { error.ZoneMismatch => return error.Skipped, error.OutOfRange => return error.Rejected, }; }, .airborne, .coarse => cpr.decodeGlobalAirborne(even.encoded, odd.encoded, reported.frame) catch |err| switch (err) { error.ZoneMismatch => return error.Skipped, error.OutOfRange => return error.Rejected, }, }; // Beyond the receiver's stated range it is not a position, it is a // mis-resolution that happens to look like one. if (self.receiver.max_range > 0) { if (self.receiver.position) |antenna| { if (geo.sphere.distance(antenna, position) > self.receiver.max_range) { self.counters.cpr_global_range_checks += 1; return error.Rejected; } } } // A multilateration result was computed from arrival times, not // decoded, so the speed check does not apply to it. if (mm.source == .mlat) return .{ .position = position, .nic = nic, .rc = rc }; if (aircraft.position.isValid(now) and aircraft.position.value.nic >= nic and !rcIsWorse(aircraft.position.value.rc, rc) and !self.speedCheck(aircraft, position, now, reported.type == .surface)) { self.counters.cpr_global_speed_checks += 1; return error.Rejected; } return .{ .position = position, .nic = nic, .rc = rc }; } /// Resolve a position from a single message, against the nearest thing to /// a known location we have. fn localPosition(self: *Tracker, aircraft: *Aircraft, mm: *const Message, now: u64) PositionError!FixedPosition { const reported = mm.cpr.?; const surface = reported.type == .surface; const half = switch (reported.frame) { .even => aircraft.cpr_even.value, .odd => aircraft.cpr_odd.value, }; var nic = half.nic; var rc = half.rc; var range_limit: f64 = 0; const reference = if (aircraft.position.isValid(now)) blk: { const last = aircraft.position.value; nic = @min(nic, last.nic); if (rcIsWorse(last.rc, rc)) rc = last.rc; // An aircraft cannot have gone far since its last position, and // the CPR cell is much larger than this, so the answer is // unambiguous. range_limit = 50e3; break :blk last.position; } else if (!surface) blk: { const antenna = self.receiver.position orelse return error.Skipped; // Against the receiver rather than a previous position there is // real ambiguity to guard against. The airborne cell is at least // 360 nautical miles across, so a report from beyond half a cell // resolves to a position the same distance away in the wrong // direction. Only the receiver's stated range rules that out. if (self.receiver.max_range == 0) return error.Skipped; const half_cell = meters_per_nautical_mile * 180; const whole_cell = meters_per_nautical_mile * 360; if (self.receiver.max_range <= half_cell) { range_limit = self.receiver.max_range; } else if (self.receiver.max_range < whole_cell) { range_limit = whole_cell - self.receiver.max_range; } else { return error.Skipped; } break :blk antenna; } else return error.Skipped; const position = cpr.decodeRelative( reference, reported.encoded, reported.frame, reported.type.kind(), ) catch return error.Skipped; if (range_limit > 0 and geo.sphere.distance(reference, position) > range_limit) { self.counters.cpr_local_range_checks += 1; return error.Skipped; } if (aircraft.position.isValid(now) and aircraft.position.value.nic >= nic and !rcIsWorse(aircraft.position.value.rc, rc) and !self.speedCheck(aircraft, position, now, surface)) { self.counters.cpr_local_speed_checks += 1; return error.Skipped; } return .{ .position = position, .nic = nic, .rc = rc }; } /// Whether the aircraft could plausibly have travelled from its last /// known position to this one in the time available. fn speedCheck(self: *const Tracker, aircraft: *const Aircraft, position: cpr.Position, now: u64, surface: bool) bool { _ = self; if (!aircraft.position.isValid(now)) return true; // nothing to check against const elapsed = aircraft.position.age(now); // Prefer a measured speed; airspeeds are only a rough guide to speed // over the ground, so they are inflated to be safe. var speed: f64 = if (aircraft.gs.isValid(now)) aircraft.gs.value else if (aircraft.tas.isValid(now)) @as(f64, @floatFromInt(aircraft.tas.value)) * 4.0 / 3.0 else if (aircraft.ias.isValid(now)) @as(f64, @floatFromInt(aircraft.ias.value)) * 2.0 else if (surface) 100 else 600; // Allow another third on top, and clamp into what is physically // sensible for where the aircraft is. speed = @trunc(@trunc(speed) * 4.0 / 3.0); if (surface) { speed = std.math.clamp(speed, 20, 150); } else { speed = @max(speed, 200); } // A base allowance for ordinary position error, plus the distance the // aircraft could have covered — with an extra second, since the // timestamps are not exact. const base: f64 = if (surface) 0.1e3 else 0.5e3; const range = base + (@as(f64, @floatFromInt(elapsed)) + 1000.0) / 1000.0 * (speed * meters_per_nautical_mile / 3600.0); return geo.sphere.distance(aircraft.position.value.position, position) <= range; } /// Work out how precise a position message claims to be, from its type /// and the supplements the aircraft has reported separately. fn computeNicRc(self: *const Tracker, aircraft: *const Aircraft, mm: *const Message, now: u64) struct { nic: u8, rc: u32 } { _ = self; const nic_a = aircraft.nic_a.isValid(now) and aircraft.nic_a.value != 0; const nic_b = (mm.accuracy.nic_b orelse 0) != 0; const nic_c = aircraft.nic_c.isValid(now) and aircraft.nic_c.value != 0; const version = aircraft.adsb_version orelse 0; return .{ .nic = computeNic(mm.metype, version, nic_a, nic_b, nic_c), .rc = computeRc(mm.metype, version, nic_a, nic_b, nic_c), }; } fn recordRange(self: *Tracker, position: cpr.Position) void { if (!self.receiver.range_histogram) return; const antenna = self.receiver.position orelse return; const range = geo.sphere.distance(antenna, position); const scaled = @round(range / self.receiver.max_range * range_bucket_count); const bucket: usize = if (scaled < 0) 0 else if (scaled >= range_bucket_count) range_bucket_count - 1 else @intFromFloat(scaled); self.counters.range_histogram[bucket] += 1; } /// Housekeeping: age out fields and whole aircraft, and match up Mode A/C /// replies with what is being tracked properly. Rate-limited internally /// to once a second, so it is safe to call from the main loop. pub fn periodic(self: *Tracker, now: u64) void { if (now < self.next_periodic_ms) return; self.next_periodic_ms = now + 1000; self.removeStale(now); self.matchModeAc(now); } fn removeStale(self: *Tracker, now: u64) void { var index: usize = 0; while (index < self.aircraft.count()) { const aircraft = self.aircraft.values()[index]; const age = now -| aircraft.seen; const gone = age > aircraft_ttl_ms or (!aircraft.reliable and age > unreliable_aircraft_ttl_ms); if (!gone) { aircraft.expireAll(now); index += 1; continue; } // An aircraft that was heard exactly once was probably never // there: a message with a corrupt address decodes into one. if (aircraft.messages == 1) self.counters.single_message_aircraft += 1; if (!aircraft.reliable) self.counters.unreliable_aircraft += 1; self.gpa.destroy(aircraft); self.aircraft.orderedRemoveAt(index); } } /// Try to attribute Mode A/C replies to aircraft that are being tracked /// through Mode S, so that the same aircraft is not counted twice. fn matchModeAc(self: *Tracker, now: u64) void { self.mode_ac.match = @splat(0); for (self.aircraft.values()) |aircraft| { // Only aircraft heard from very recently; a Mode A/C reply is // being matched against what the aircraft is doing now. if (now -| aircraft.seen > 5000) continue; if (aircraft.squawk.isValid(now)) { const index = mode_ac.toIndex(aircraft.squawk.value); if (self.mode_ac.isLive(index)) { aircraft.mode_a_hit = true; self.mode_ac.recordMatch(index, aircraft.address); } } if (aircraft.altitude_baro.isValid(now)) { // Mode C has hundred-foot resolution and the aircraft's // altitude is not exactly on a step, so check the // neighbouring codes too. const hundreds = hundredsOfFeet(aircraft.altitude_baro.value); for ([_]i32{ hundreds, hundreds + 1, hundreds - 1 }) |candidate| { if (candidate < std.math.minInt(i16) or candidate > std.math.maxInt(i16)) continue; const squawk = mode_ac.fromAltitude(@intCast(candidate)) orelse continue; const index = mode_ac.toIndex(squawk); if (!self.mode_ac.isLive(index)) continue; aircraft.mode_c_hit = true; self.mode_ac.recordMatch(index, aircraft.address); } } } for (0..4096) |i| { const index: u12 = @intCast(i); if (self.mode_ac.count[index] == 0) continue; if (!self.mode_ac.isLive(index)) { self.mode_ac.age[index] += 1; if (self.mode_ac.age[index] > 15) { // Not heard for a while; forget it entirely. self.mode_ac.count[index] = 0; self.mode_ac.last_count[index] = 0; self.mode_ac.age[index] = 0; } } else if (self.mode_ac.match[index] != 0) { // Start a matched code off old, so that it disappears // promptly once the Mode S track it belongs to changes or // goes away. self.mode_ac.age[index] = 10; } else { self.mode_ac.age[index] = 0; } self.mode_ac.last_count[index] = self.mode_ac.count[index]; } } }; /// Milliseconds between two timestamps, whichever way round they are. fn timeBetween(a: u64, b: u64) u64 { return if (a >= b) a - b else b - a; } /// An altitude in feet, whatever it was reported in. fn altitudeToFeet(altitude: message.Altitude) i32 { return switch (altitude.unit) { .feet => altitude.value, // Truncating towards zero, as upstream's int conversion does. .meters => @intFromFloat(@as(f64, @floatFromInt(altitude.value)) / 0.3048), }; } /// An altitude rounded to the hundred-foot steps Mode C reports in. fn hundredsOfFeet(feet: i32) i32 { return @divTrunc(feet + 49, 100); } /// Whether one radius of containment is worse than another. Zero means /// unknown, which is worse than any known value. fn rcIsWorse(left: u32, right: u32) bool { if (left == rc_unknown and right == rc_unknown) return false; if (left == rc_unknown) return true; if (right == rc_unknown) return false; return left > right; } /// The Navigation Integrity Category a position message type implies. /// /// The type alone is not enough for several of them: the same type means /// different precisions depending on the aircraft's ADS-B version and on the /// NIC supplement bits, which arrive in entirely different messages. ED-102 /// tables 2-14, N-4 and N-11. fn computeNic(metype: u5, version: u3, nic_a: bool, nic_b: bool, nic_c: bool) u8 { return switch (metype) { 5, 9, 20 => 11, 6, 10, 21 => 10, 7 => switch (version) { 2 => if (nic_a and !nic_c) 9 else 8, 1 => if (nic_a) 9 else 8, else => 8, }, 8 => switch (version) { 2 => if (nic_a and nic_c) 7 else if (nic_a != nic_c) 6 else 0, else => 0, }, 11 => switch (version) { 2 => if (nic_a and nic_b) 9 else 8, 1 => if (nic_a) 9 else 8, else => 8, }, 12 => 7, 13 => 6, 14 => 5, 15 => 4, 16 => if (nic_a and nic_b) 3 else 2, 17 => 1, else => 0, }; } /// The radius of containment, in metres, that a position message type /// implies: the circle the aircraft claims to be inside. fn computeRc(metype: u5, version: u3, nic_a: bool, nic_b: bool, nic_c: bool) u32 { return switch (metype) { 5, 9, 20 => 8, // 7.5m 6, 10, 21 => 25, 7 => switch (version) { 2 => if (nic_a and !nic_c) 75 else 186, // 185.2m, 0.1NM 1 => if (nic_a) 75 else 186, else => 186, }, 8 => switch (version) { 2 => if (nic_a and nic_c) 371 // 370.4m, 0.2NM else if (nic_a and !nic_c) 556 // 555.6m, 0.3NM else if (!nic_a and nic_c) 1111 // 0.6NM else rc_unknown, else => rc_unknown, }, 11 => switch (version) { 2 => if (nic_a and nic_b) 75 else 186, 1 => if (nic_a) 75 else 186, else => 186, }, 12 => 371, // 370.4m, 0.2NM 13 => switch (version) { 2 => if (!nic_a and nic_b) 556 // 555.6m, 0.3NM else if (!nic_a and !nic_b) 926 // 0.5NM else if (nic_a and nic_b) 1112 // 1111.2m, 0.6NM else rc_unknown, // a combination the tables do not define 1 => if (nic_a) 1112 else 926, else => 926, }, 14 => 1852, // 1NM 15 => 3704, // 2NM 16 => switch (version) { 2 => if (nic_a and nic_b) 7408 else 14816, // 4NM or 8NM 1 => if (nic_a) 7408 else 14816, else => 18520, // 10NM }, 17 => 37040, // 20NM else => rc_unknown, }; } /// The NACp an ADS-B version 0 aircraft implies by the type of position /// message it sent, since it has no field to state one. ED-102A table N-7. fn version0Nacp(mm: *const Message) ?u4 { if (!mm.format.isAny(&.{ 17, 18 })) return null; return switch (mm.metype) { 0 => 0, 5 => 11, 6 => 10, 7 => 8, 8 => 0, 9 => 11, 10 => 10, 11 => 8, 12 => 7, 13 => 6, 14 => 5, 15 => 4, 16, 17 => 1, 18 => 0, 20 => 11, 21 => 10, 22 => 0, else => null, }; } /// The SIL such an aircraft implies. ED-102A table N-8. fn version0Sil(mm: *const Message) ?u2 { if (!mm.format.isAny(&.{ 17, 18 })) return null; return switch (mm.metype) { 0 => 0, 5...17 => 2, 18 => 0, 20, 21 => 2, 22 => 0, else => null, }; } const testing = std.testing; fn testMessage(address: u32, now: u64, source: Source) Message { var mm: Message = .empty; mm.format = .{ .mode_s = 17 }; mm.address = address; mm.source = source; mm.system_timestamp_ms = now; mm.reliable = true; return mm; } test "a value from a better source holds off a worse one until it goes stale" { var field: Tracked(i32, 15, 70) = .init; try testing.expect(field.set(1000, .adsb, 100)); try testing.expectEqual(@as(?i32, 100), field.get(1000)); // Still fresh: a Mode S reply may not overwrite an ADS-B report. try testing.expect(!field.set(5000, .mode_s, 200)); try testing.expectEqual(@as(?i32, 100), field.get(5000)); // Past the stale time it may. try testing.expect(field.set(20_000, .mode_s, 200)); try testing.expectEqual(@as(?i32, 200), field.get(20_000)); // Past the expiry time it is gone. try testing.expectEqual(@as(?i32, null), field.get(20_000 + 70_001)); } test "an equally good source always wins" { var field: Tracked(i32, 15, 70) = .init; try testing.expect(field.set(1000, .adsb, 100)); try testing.expect(field.set(1001, .adsb, 200)); try testing.expectEqual(@as(?i32, 200), field.get(1001)); } test "combined validity takes the worse source and the earlier deadlines" { const a: Validity = .{ .source = .adsb, .updated = 100, .stale = 200, .expires = 300 }; const b: Validity = .{ .source = .mode_s, .updated = 150, .stale = 180, .expires = 400 }; const combined: Validity = .combine(a, b); try testing.expectEqual(Source.mode_s, combined.source); try testing.expectEqual(@as(u64, 150), combined.updated); try testing.expectEqual(@as(u64, 180), combined.stale); try testing.expectEqual(@as(u64, 300), combined.expires); // An invalid input contributes nothing. try testing.expectEqual(a, Validity.combine(a, .invalid)); try testing.expectEqual(a, Validity.combine(.invalid, a)); } test "an unknown radius of containment is worse than any known one" { try testing.expect(!rcIsWorse(rc_unknown, rc_unknown)); try testing.expect(rcIsWorse(rc_unknown, 186)); try testing.expect(!rcIsWorse(186, rc_unknown)); try testing.expect(rcIsWorse(1852, 186)); try testing.expect(!rcIsWorse(186, 1852)); } test "an aircraft is created and found by address" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); var mm = testMessage(0x4840d6, 1000, .adsb); mm.altitude_baro = .{ .value = 38000, .unit = .feet }; const aircraft = (try tracker.update(&mm)).?; try testing.expectEqual(@as(u32, 0x4840d6), aircraft.address); try testing.expectEqual(@as(?i32, 38000), aircraft.altitude_baro.get(1000)); try testing.expectEqual(@as(u64, 1), tracker.counters.unique_aircraft); // The same address finds the same record. var again = testMessage(0x4840d6, 2000, .adsb); try testing.expectEqual(aircraft, (try tracker.update(&again)).?); try testing.expectEqual(@as(u64, 1), tracker.counters.unique_aircraft); try testing.expectEqual(aircraft, tracker.find(0x4840d6).?); } test "a message with no address is not tracked" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); var mm = testMessage(0, 1000, .adsb); try testing.expectEqual(@as(?*Aircraft, null), try tracker.update(&mm)); try testing.expectEqual(@as(usize, 0), tracker.aircraft.count()); } test "a Mode A/C reply is counted, not tracked" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); var mm: Message = .empty; mm.format = .mode_ac; mm.squawk = 0x7700; mm.source = .mode_ac; try testing.expectEqual(@as(?*Aircraft, null), try tracker.update(&mm)); try testing.expectEqual(@as(usize, 0), tracker.aircraft.count()); try testing.expectEqual(@as(u32, 1), tracker.mode_ac.count[mode_ac.toIndex(0x7700)]); } test "an unreliable track discards unreliable messages until it earns trust" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); // A DF20 is never reliable on its own. var mm = testMessage(0x4840d6, 1000, .mode_s); mm.format = .{ .mode_s = 20 }; mm.reliable = false; mm.altitude_baro = .{ .value = 38000, .unit = .feet }; const aircraft = (try tracker.update(&mm)).?; try testing.expect(!aircraft.reliable); try testing.expectEqual(@as(u64, 1), aircraft.discarded); try testing.expectEqual(@as(?i32, null), aircraft.altitude_baro.get(1000)); // Five messages of any sort is enough to believe in the track. for (0..4) |i| { var more = testMessage(0x4840d6, 1000 + i, .mode_s); more.format = .{ .mode_s = 20 }; more.reliable = false; _ = try tracker.update(&more); } try testing.expect(aircraft.reliable); var accepted = testMessage(0x4840d6, 2000, .mode_s); accepted.format = .{ .mode_s = 20 }; accepted.reliable = false; accepted.altitude_baro = .{ .value = 38000, .unit = .feet }; _ = try tracker.update(&accepted); try testing.expectEqual(@as(?i32, 38000), aircraft.altitude_baro.get(2000)); } test "two clean DF17s make a track reliable" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); var first = testMessage(0x4840d6, 1000, .adsb); const aircraft = (try tracker.update(&first)).?; try testing.expect(!aircraft.reliable); var second = testMessage(0x4840d6, 1001, .adsb); _ = try tracker.update(&second); try testing.expect(aircraft.reliable); } test "a global position solve needs an even and an odd message" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); // The worked-example pair, from aircraft 40:62:1D. var even = testMessage(0x40621d, 1000, .adsb); even.metype = 11; even.cpr = .{ .frame = .even, .type = .airborne, .encoded = .{ .latitude = 93000, .longitude = 51372 } }; const aircraft = (try tracker.update(&even)).?; // One half alone resolves nothing. try testing.expectEqual(@as(?message.DecodedPosition, null), even.decoded_position); try testing.expect(!aircraft.position.isValid(1000)); var odd = testMessage(0x40621d, 2000, .adsb); odd.metype = 11; odd.cpr = .{ .frame = .odd, .type = .airborne, .encoded = .{ .latitude = 74158, .longitude = 50194 } }; _ = try tracker.update(&odd); // The odd message arrived last, so the answer is its position rather // than the even one's — a few metres north-east, one message later. const fixed = odd.decoded_position.?; try testing.expectApproxEqAbs(@as(f64, 52.265780), fixed.position.latitude, 1e-5); try testing.expectApproxEqAbs(@as(f64, 3.938913), fixed.position.longitude, 1e-5); try testing.expect(!fixed.relative); // Type 11 with no supplements is NIC 8, Rc 185.2m. try testing.expectEqual(@as(u8, 8), fixed.nic); try testing.expectEqual(@as(u32, 186), fixed.rc); try testing.expect(aircraft.position.isValid(2000)); try testing.expectEqual(@as(u64, 1), tracker.counters.cpr_global_ok); } test "a pair too far apart in time is not combined" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); var even = testMessage(0x40621d, 1000, .adsb); even.metype = 11; even.cpr = .{ .frame = .even, .type = .airborne, .encoded = .{ .latitude = 93000, .longitude = 51372 } }; _ = try tracker.update(&even); // Eleven seconds later: beyond the ten-second airborne window. var odd = testMessage(0x40621d, 12_000, .adsb); odd.metype = 11; odd.cpr = .{ .frame = .odd, .type = .airborne, .encoded = .{ .latitude = 74158, .longitude = 50194 } }; _ = try tracker.update(&odd); try testing.expectEqual(@as(?message.DecodedPosition, null), odd.decoded_position); try testing.expectEqual(@as(u64, 0), tracker.counters.cpr_global_ok); } test "a later single message is resolved against the last known position" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); var even = testMessage(0x40621d, 1000, .adsb); even.metype = 11; even.cpr = .{ .frame = .even, .type = .airborne, .encoded = .{ .latitude = 93000, .longitude = 51372 } }; _ = try tracker.update(&even); var odd = testMessage(0x40621d, 2000, .adsb); odd.metype = 11; odd.cpr = .{ .frame = .odd, .type = .airborne, .encoded = .{ .latitude = 74158, .longitude = 50194 } }; _ = try tracker.update(&odd); // A third message far enough after the first that the pair has gone // stale, but close enough to the known position to solve against it. var later = testMessage(0x40621d, 20_000, .adsb); later.metype = 11; later.cpr = .{ .frame = .even, .type = .airborne, .encoded = .{ .latitude = 93000, .longitude = 51372 } }; _ = try tracker.update(&later); const fixed = later.decoded_position.?; try testing.expect(fixed.relative); try testing.expectApproxEqAbs(@as(f64, 52.257202), fixed.position.latitude, 1e-5); try testing.expectEqual(@as(u64, 1), tracker.counters.cpr_local_ok); } test "a position beyond the receiver's range is rejected and the pair discarded" { var tracker: Tracker = .init(testing.allocator, .{ .position = .{ .latitude = 41.6, .longitude = -93.6 }, // Des Moines .max_range = 400e3, }); defer tracker.deinit(); // The worked-example aircraft is over the North Sea, which is not within // 400km of Iowa. var even = testMessage(0x40621d, 1000, .adsb); even.metype = 11; even.cpr = .{ .frame = .even, .type = .airborne, .encoded = .{ .latitude = 93000, .longitude = 51372 } }; const aircraft = (try tracker.update(&even)).?; var odd = testMessage(0x40621d, 2000, .adsb); odd.metype = 11; odd.cpr = .{ .frame = .odd, .type = .airborne, .encoded = .{ .latitude = 74158, .longitude = 50194 } }; _ = try tracker.update(&odd); try testing.expectEqual(@as(?message.DecodedPosition, null), odd.decoded_position); try testing.expectEqual(@as(u64, 1), tracker.counters.cpr_global_range_checks); try testing.expectEqual(@as(u64, 1), tracker.counters.cpr_global_bad); // Both halves are thrown away, so the next pair starts fresh. try testing.expect(!aircraft.cpr_even.isValid(2000)); try testing.expect(!aircraft.cpr_odd.isValid(2000)); } test "headings are filed by what the aircraft says they mean" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); var mm = testMessage(0x4840d6, 1000, .adsb); mm.heading = .{ .degrees = 90, .type = .ground_track }; const aircraft = (try tracker.update(&mm)).?; try testing.expectEqual(@as(?f32, 90), aircraft.track.get(1000)); try testing.expectEqual(@as(?f32, null), aircraft.mag_heading.get(1000)); // "Magnetic or true" defers to the aircraft's heading reference, which // defaults to magnetic. var deferred = testMessage(0x4840d6, 2000, .adsb); deferred.heading = .{ .degrees = 45, .type = .magnetic_or_true }; _ = try tracker.update(&deferred); try testing.expectEqual(@as(?f32, 45), aircraft.mag_heading.get(2000)); // Once the aircraft says it references true north, the same field goes // somewhere else. var status = testMessage(0x4840d6, 3000, .adsb); status.opstatus = .{ .version = 2, .hrd = .true_heading }; _ = try tracker.update(&status); var later = testMessage(0x4840d6, 4000, .adsb); later.heading = .{ .degrees = 200, .type = .magnetic_or_true }; _ = try tracker.update(&later); try testing.expectEqual(@as(?f32, 200), aircraft.true_heading.get(4000)); } test "a geometric altitude is derived from a barometric one plus a delta" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); var mm = testMessage(0x4840d6, 1000, .adsb); mm.altitude_baro = .{ .value = 38000, .unit = .feet }; mm.geom_delta = 300; const aircraft = (try tracker.update(&mm)).?; try testing.expectEqual(@as(?i32, 38300), aircraft.altitude_geom.get(1000)); } test "an aircraft heard once is reaped quickly" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); var mm = testMessage(0x4840d6, 1000, .adsb); _ = try tracker.update(&mm); try testing.expectEqual(@as(usize, 1), tracker.aircraft.count()); // Not yet: an unreliable track lives a minute. tracker.periodic(50_000); try testing.expectEqual(@as(usize, 1), tracker.aircraft.count()); tracker.periodic(70_000); try testing.expectEqual(@as(usize, 0), tracker.aircraft.count()); try testing.expectEqual(@as(u64, 1), tracker.counters.single_message_aircraft); try testing.expectEqual(@as(u64, 1), tracker.counters.unreliable_aircraft); } test "a reliable aircraft lives five minutes and its fields expire first" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); for (0..2) |i| { var mm = testMessage(0x4840d6, 1000 + i, .adsb); mm.altitude_baro = .{ .value = 38000, .unit = .feet }; _ = try tracker.update(&mm); } const aircraft = tracker.find(0x4840d6).?; try testing.expect(aircraft.reliable); // The altitude expires seventy seconds after it arrived... tracker.periodic(100_000); try testing.expectEqual(@as(usize, 1), tracker.aircraft.count()); try testing.expectEqual(@as(?i32, null), aircraft.altitude_baro.get(100_000)); // ...but the aircraft itself survives for five minutes. tracker.periodic(200_000); try testing.expectEqual(@as(usize, 1), tracker.aircraft.count()); tracker.periodic(400_000); try testing.expectEqual(@as(usize, 0), tracker.aircraft.count()); } test "aircraft are presented most recently discovered first" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); for ([_]u32{ 0x100001, 0x100002, 0x100003 }) |address| { var mm = testMessage(address, 1000, .adsb); _ = try tracker.update(&mm); } var seen: std.ArrayList(u32) = .empty; defer seen.deinit(testing.allocator); var it = tracker.iterator(); while (it.next()) |aircraft| try seen.append(testing.allocator, aircraft.address); try testing.expectEqualSlices(u32, &.{ 0x100003, 0x100002, 0x100001 }, seen.items); } test "Mode A/C replies are matched against tracked squawks" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); // An aircraft squawking 1200, tracked through Mode S. for (0..5) |i| { var mm = testMessage(0x4840d6, 1000 + i, .adsb); mm.squawk = 0x1200; _ = try tracker.update(&mm); } const aircraft = tracker.find(0x4840d6).?; try testing.expect(!aircraft.mode_a_hit); // Three bare Mode A replies in a check period is not enough to be sure // the code belongs to anything. for (0..3) |_| { var reply: Message = .empty; reply.format = .mode_ac; reply.squawk = 0x1200; reply.source = .mode_ac; _ = try tracker.update(&reply); } tracker.periodic(2000); try testing.expect(!aircraft.mode_a_hit); // Four in the next one is. The threshold is a rate, not a total: the // count is baselined at every check, so replies dribbling in one per // second never add up. for (0..4) |_| { var reply: Message = .empty; reply.format = .mode_ac; reply.squawk = 0x1200; reply.source = .mode_ac; _ = try tracker.update(&reply); } tracker.periodic(4000); try testing.expect(aircraft.mode_a_hit); // And the code is attributed to that aircraft rather than left loose. try testing.expectEqual(@as(u32, 0x4840d6), tracker.mode_ac.match[mode_ac.toIndex(0x1200)]); } test "version 0 aircraft have their accuracy figures inferred" { var tracker: Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); var mm = testMessage(0x4840d6, 1000, .adsb); mm.metype = 11; // airborne position const aircraft = (try tracker.update(&mm)).?; // Nothing in the message said either of these; the message type did. try testing.expectEqual(@as(?u4, 8), mm.accuracy.nac_p); try testing.expectEqual(message.SilType.unknown, mm.accuracy.sil_type); try testing.expectEqual(@as(u2, 2), mm.accuracy.sil); try testing.expectEqual(@as(?u4, 8), aircraft.nac_p.get(1000)); } test "altitudes in metres are converted to feet" { try testing.expectEqual(@as(i32, 38000), altitudeToFeet(.{ .value = 38000, .unit = .feet })); try testing.expectEqual(@as(i32, 3280), altitudeToFeet(.{ .value = 1000, .unit = .meters })); }