// 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 //! Comm-B replies: guessing which register a transponder answered with. //! //! A Comm-B reply carries 56 bits of payload and no indication of what those //! bits are. The ground station that interrogated the aircraft knows, because //! it asked; a passive receiver listening to the reply does not. So the only //! way to read one is to try every register in turn and see which //! interpretation produces something an aircraft could plausibly be doing — //! an altitude between a thousand and fifty thousand feet, a roll angle under //! forty degrees, a Mach number in the subsonic range. //! //! Each decoder here returns a score rather than a yes or no, and the highest //! score wins. A tie is reported as `.ambiguous` rather than guessed at, //! because a wrong guess does not produce nothing — it produces a plausible //! aircraft doing something it is not. //! //! The scores are not calibrated against anything; they are upstream's, tuned //! against real traffic, and the numbers matter only relative to each other. const std = @import("std"); const ais = @import("ais.zig"); const bits = @import("bits.zig"); const message = @import("message.zig"); const Message = message.Message; /// One register's decoder: score how plausible this reply is as that /// register, and if `store` is set, write what it decoded into the message. /// /// A score of zero means "definitely not this register". const Decoder = *const fn (*Message, bool) i32; /// Every register we know how to recognise, in upstream's order. const decoders = [_]Decoder{ decodeEmptyResponse, decodeBds10, decodeBds20, decodeBds30, decodeBds17, decodeBds40, decodeBds50, decodeBds60, decodeBds44, decodeBds05, }; /// Work out what a Comm-B reply contained and fill in whatever it said. pub fn decode(mm: *Message) void { // A reply with a downlink request or a utility message set is probably // noise: nothing in service seems to use the multisite protocol those // fields belong to. A reply that needed error correction is not worth // guessing at either, since a wrong bit changes which register wins. if (mm.raw.dr != 0 or mm.raw.um != 0 or mm.corrected_bits > 0) { mm.commb_format = .not_decoded; return; } var best_score: i32 = 0; var best: ?Decoder = null; var ambiguous = false; for (decoders) |decoder| { const score = decoder(mm, false); if (score > best_score) { best_score = score; best = decoder; ambiguous = false; } else if (score == best_score) { ambiguous = true; } } if (best) |decoder| { if (ambiguous) { mm.commb_format = .ambiguous; } else { _ = decoder(mm, true); } } else { mm.commb_format = .unknown; } } /// A reply with nothing in it. /// /// All zeros is the common form, but transponders also answer `40`, `50` or /// `60` followed by zeros — apparently when asked for BDS4,0, BDS5,0 or /// BDS6,0 and having nothing loaded for it. They arrive in bursts of one of /// each from the same aircraft, which is how the pattern was spotted. fn decodeEmptyResponse(mm: *Message, store: bool) i32 { switch (mm.raw.mb[0]) { 0x00, 0x40, 0x50, 0x60 => {}, else => return 0, } for (mm.raw.mb[1..]) |byte| { if (byte != 0) return 0; } if (store) mm.commb_format = .empty_response; return 56; } /// BDS1,0 data link capability report. fn decodeBds10(mm: *Message, store: bool) i32 { const msg = &mm.raw.mb; if (msg[0] != 0x10) return 0; if (bits.get(msg, 10, 14) != 0) return 0; if (store) mm.commb_format = .datalink_caps; return 56; } /// BDS1,7 common usage GICB capability report: which other registers this /// transponder will answer. /// /// There is no identifying byte, so this one is recognised purely by whether /// the advertised set of capabilities is a combination that real equipment /// has. Extended squitter support comes as a block of five, BDS2,0 is on /// almost everything, and the waypoint registers are on almost nothing. fn decodeBds17(mm: *Message, store: bool) i32 { const msg = &mm.raw.mb; if (bits.get(msg, 25, 56) != 0) return 0; var score: i32 = 0; if (bits.flag(msg, 7)) { score += 1; // BDS2,0 aircraft identification } else { score -= 2; // ...which is on almost everything, so its absence is odd } // Registers that real transponders almost never implement. if (bits.flag(msg, 10)) score -= 2; // BDS4,1 next waypoint identifier if (bits.flag(msg, 11)) score -= 2; // BDS4,2 next waypoint position if (bits.flag(msg, 12)) score -= 2; // BDS4,3 next waypoint information if (bits.flag(msg, 13)) score -= 1; // BDS4,4 meteorological routine report if (bits.flag(msg, 14)) score -= 1; // BDS4,5 meteorological hazard report if (bits.flag(msg, 20)) score -= 2; // BDS5,4 waypoint 1 if (bits.flag(msg, 21)) score -= 2; // BDS5,5 waypoint 2 if (bits.flag(msg, 22)) score -= 2; // BDS5,6 waypoint 3 const es = [5]bool{ bits.flag(msg, 1), bits.flag(msg, 2), bits.flag(msg, 3), bits.flag(msg, 4), bits.flag(msg, 5), }; if (es[0] and es[1] and es[2] and es[3] and es[4]) { // Extended squitter capable. score += 5; if (bits.flag(msg, 6)) score += 1; // ES event-driven information } else if (!es[0] and !es[1] and !es[2] and !es[3] and !es[4] and !bits.flag(msg, 6)) { // Not extended squitter capable at all. score += 1; } else if (!es[0] and !es[1] and es[2] and es[3] and es[4]) { // Extended squitter, but no position registers. score += 3; } else { // Some other combination, which no real equipment reports. score -= 12; } if (bits.flag(msg, 16) and bits.flag(msg, 24)) { // Track/turn and heading/speed, which come as a pair. score += 2; if (bits.flag(msg, 9)) score += 1; // vertical intent as well } else if (!bits.flag(msg, 16) and !bits.flag(msg, 24) and !bits.flag(msg, 9)) { score += 1; } else { score -= 6; } if (store) mm.commb_format = .gicb_caps; return score; } /// BDS2,0 aircraft identification: the callsign. fn decodeBds20(mm: *Message, store: bool) i32 { const msg = &mm.raw.mb; if (msg[0] != 0x20) return 0; const callsign = ais.decodeCallsign(msg, 9); // The more characters that are legal in a callsign, the more likely this // really is one. Anything outside the legal set rules the register out // entirely, except for the padding character. var score: i32 = 8; var usable = true; for (callsign) |character| { switch (character) { 'A'...'Z', '0'...'9', ' ' => score += 6, // All-zero payloads decode to `@@@@@@@@`. That is a real BDS2,0 // reply and should be recognised as one, but the callsign in it // is not a callsign. '@' => usable = false, else => return 0, } } if (store) { mm.commb_format = .aircraft_ident; if (usable) mm.callsign = callsign; } return score; } /// BDS3,0 ACAS resolution advisory: what the collision avoidance system is /// telling the pilot to do. fn decodeBds30(mm: *Message, store: bool) i32 { if (mm.raw.mb[0] != 0x30) return 0; if (store) mm.commb_format = .acas_ra; // The identifying byte is enough; the contents are not checked. return 56; } /// BDS4,0 selected vertical intention: the altitudes in the autopilot. fn decodeBds40(mm: *Message, store: bool) i32 { const msg = &mm.raw.mb; const mcp_valid = bits.flag(msg, 1); const mcp_raw = bits.get(msg, 2, 13); const fms_valid = bits.flag(msg, 14); const fms_raw = bits.get(msg, 15, 26); const baro_valid = bits.flag(msg, 27); const baro_raw = bits.get(msg, 28, 39); const reserved_1 = bits.get(msg, 40, 47); const mode_valid = bits.flag(msg, 48); const mode_raw = bits.get(msg, 49, 51); const reserved_2 = bits.get(msg, 52, 53); const source_valid = bits.flag(msg, 54); const source_raw = bits.get(msg, 55, 56); if (!mcp_valid and !fms_valid and !baro_valid and !mode_valid and !source_valid) return 0; var score: i32 = 0; // A field flagged invalid must also be zero, or this is not a BDS4,0 at // all; a field flagged valid must hold something an aircraft would fly. var mcp_altitude: u32 = 0; if (mcp_valid and mcp_raw != 0) { mcp_altitude = mcp_raw * 16; if (mcp_altitude >= 1000 and mcp_altitude <= 50000) score += 13 else return 0; } else if (!mcp_valid and mcp_raw == 0) { score += 1; } else return 0; var fms_altitude: u32 = 0; if (fms_valid and fms_raw != 0) { fms_altitude = fms_raw * 16; if (fms_altitude >= 1000 and fms_altitude <= 50000) score += 13 else return 0; } else if (!fms_valid and fms_raw == 0) { score += 1; } else return 0; var qnh: f32 = 0; if (baro_valid and baro_raw != 0) { qnh = @floatCast(800.0 + @as(f64, @floatFromInt(baro_raw)) * 0.1); if (qnh >= 900 and qnh <= 1100) score += 13 else return 0; } else if (!baro_valid and baro_raw == 0) { score += 1; } else return 0; if (reserved_1 != 0) return 0; if (mode_valid) { score += 4; } else if (mode_raw == 0) { score += 1; } else return 0; if (reserved_2 != 0) return 0; if (source_valid) { score += 3; } else if (source_raw == 0) { score += 1; } else return 0; // An aircraft flying to two different altitudes at once is possible but // unusual, and altitudes are almost always dialled in round numbers. if (mcp_valid and fms_valid and mcp_altitude != fms_altitude) score -= 4; if (mcp_valid and !isRoundAltitude(mcp_altitude)) score -= 4; if (fms_valid and !isRoundAltitude(fms_altitude)) score -= 4; if (store) { mm.commb_format = .vertical_intent; if (mcp_valid) mm.nav.mcp_altitude = @intCast(mcp_altitude); if (fms_valid) mm.nav.fms_altitude = @intCast(fms_altitude); if (baro_valid) mm.nav.qnh = qnh; if (mode_valid) { mm.nav.modes = .{ .vnav = mode_raw & 4 != 0, .alt_hold = mode_raw & 2 != 0, .approach = mode_raw & 1 != 0, }; } mm.nav.altitude_source = if (!source_valid) .invalid else switch (source_raw) { 0 => .unknown, 1 => .aircraft, 2 => .mcp, 3 => .fms, else => .invalid, }; } return score; } /// Whether an altitude is within sixteen feet of a multiple of five hundred, /// which is what a pilot would actually have dialled. Sixteen feet is the /// resolution of the field. fn isRoundAltitude(altitude: u32) bool { const remainder = altitude % 500; return remainder < 16 or remainder > 484; } /// BDS5,0 track and turn report. fn decodeBds50(mm: *Message, store: bool) i32 { const msg = &mm.raw.mb; const roll_sign = bits.flag(msg, 2); const roll_raw = bits.get(msg, 3, 11); const track_sign = bits.flag(msg, 13); const track_raw = bits.get(msg, 14, 23); const gs_raw = bits.get(msg, 25, 34); const track_rate_valid = bits.flag(msg, 35); const track_rate_sign = bits.flag(msg, 36); const track_rate_raw = bits.get(msg, 37, 45); const tas_raw = bits.get(msg, 47, 56); // Every real BDS5,0 reply has all four of these; a reply missing one is // some other register. if (!bits.flag(msg, 1) or !bits.flag(msg, 12) or !bits.flag(msg, 24) or !bits.flag(msg, 46)) return 0; var score: i32 = 0; var roll: f32 = @floatCast(@as(f64, @floatFromInt(roll_raw)) * 45.0 / 256.0); if (roll_sign) roll -= 90.0; if (roll >= -40 and roll < 40) score += 11 else return 0; score += 12; var track: f32 = @floatCast(@as(f64, @floatFromInt(track_raw)) * 90.0 / 512.0); if (track_sign) track += 180.0; if (gs_raw == 0) return 0; const gs = gs_raw * 2; if (gs >= 50 and gs <= 700) score += 11 else return 0; var track_rate: f32 = 0; if (track_rate_valid) { track_rate = @floatCast(@as(f64, @floatFromInt(track_rate_raw)) * 8.0 / 256.0); if (track_rate_sign) track_rate -= 16; if (track_rate >= -10.0 and track_rate <= 10.0) score += 11 else return 0; } else if (track_rate_raw == 0 and !track_rate_sign) { score += 1; } else return 0; if (tas_raw == 0) return 0; const tas = tas_raw * 2; if (tas >= 50 and tas <= 700) score += 11 else return 0; // Upstream also has a penalty here for ground speed and true airspeed // disagreeing by more than 150 knots, but it compares the two validity // flags rather than the two speeds, and both are known to be set by this // point — so the penalty can never apply and is not reproduced. // A banked aircraft turns at a rate its speed and bank angle determine, // so a track rate that does not match the roll is a sign that this is not // really a BDS5,0. if (tas > 0 and track_rate_valid) { const turn_rate = 68625.0 * @tan(@as(f64, roll) * std.math.pi / 180.0) / (@as(f64, @floatFromInt(tas * 20)) * std.math.pi); if (@abs(turn_rate - @as(f64, track_rate)) > 2.0) score -= 6; } if (store) { mm.commb_format = .track_turn; mm.roll = roll; mm.heading = .{ .degrees = track, .type = .ground_track }; mm.gs = .exact(@floatFromInt(gs)); if (track_rate_valid) mm.track_rate = track_rate; mm.tas = tas; } return score; } /// BDS6,0 heading and speed report. fn decodeBds60(mm: *Message, store: bool) i32 { const msg = &mm.raw.mb; const heading_sign = bits.flag(msg, 2); const heading_raw = bits.get(msg, 3, 12); const ias_raw = bits.get(msg, 14, 23); const mach_raw = bits.get(msg, 25, 34); const baro_rate_valid = bits.flag(msg, 35); const baro_rate_sign = bits.flag(msg, 36); const baro_rate_raw = bits.get(msg, 37, 45); const inertial_rate_valid = bits.flag(msg, 46); const inertial_rate_sign = bits.flag(msg, 47); const inertial_rate_raw = bits.get(msg, 48, 56); if (!bits.flag(msg, 1) or !bits.flag(msg, 13) or !bits.flag(msg, 24) or (!baro_rate_valid and !inertial_rate_valid)) return 0; var score: i32 = 12; var heading: f32 = @floatCast(@as(f64, @floatFromInt(heading_raw)) * 90.0 / 512.0); if (heading_sign) heading += 180.0; if (ias_raw == 0) return 0; const ias = ias_raw; if (ias >= 50 and ias <= 700) score += 11 else return 0; if (mach_raw == 0) return 0; const mach: f32 = @floatCast(@as(f64, @floatFromInt(mach_raw)) * 2.048 / 512.0); if (mach >= 0.1 and mach <= 0.9) score += 11 else return 0; var baro_rate: i32 = 0; if (baro_rate_valid) { baro_rate = @as(i32, @intCast(baro_rate_raw)) * 32; if (baro_rate_sign) baro_rate -= 16384; if (baro_rate >= -6000 and baro_rate <= 6000) score += 11 else return 0; } else if (baro_rate_raw == 0) { score += 1; } else return 0; var inertial_rate: i32 = 0; if (inertial_rate_valid) { inertial_rate = @as(i32, @intCast(inertial_rate_raw)) * 32; if (inertial_rate_sign) inertial_rate -= 16384; if (inertial_rate >= -6000 and inertial_rate <= 6000) score += 11 else return 0; } else if (inertial_rate_raw == 0) { score += 1; } else return 0; // The two vertical rates measure the same thing by different means, so // they should agree. if (baro_rate_valid and inertial_rate_valid) { if (@abs(baro_rate - inertial_rate) > 2000) score -= 12; } if (store) { mm.commb_format = .heading_speed; mm.heading = .{ .degrees = heading, .type = .magnetic_heading }; mm.ias = ias; mm.mach = mach; if (baro_rate_valid) mm.baro_rate = baro_rate; // Inertial data is treated as a geometric rate everywhere else, so it // is treated as one here. if (inertial_rate_valid) mm.geom_rate = inertial_rate; } return score; } /// BDS4,4 meteorological routine air report: the weather the aircraft is /// flying through, from its own sensors. fn decodeBds44(mm: *Message, store: bool) i32 { const msg = &mm.raw.mb; const source = bits.get(msg, 1, 4); const wind_valid = bits.flag(msg, 5); const wind_speed_raw = bits.get(msg, 6, 14); const wind_dir_raw = bits.get(msg, 15, 23); // ICAO 9871 gives bit 24 as a sign and bits 25-34 as the temperature, // which does not work: that is one bit too many for the range it claims. // Observed traffic fits bit 24 being a status flag, bit 25 the sign and // bits 26-34 the value, so that is what is decoded here. const sat_valid = bits.flag(msg, 24); const sat_sign = bits.flag(msg, 25); const sat_raw = bits.get(msg, 26, 34); const pressure_valid = bits.flag(msg, 35); const pressure_raw = bits.get(msg, 36, 46); const turbulence_valid = bits.flag(msg, 47); const turbulence_raw = bits.get(msg, 48, 49); const humidity_valid = bits.flag(msg, 50); const humidity_raw = bits.get(msg, 51, 56); // Source 0 is invalid and 5 and up are reserved. if (source == 0 or source >= 5) return 0; // Every valid report seen in the wild carries at least a temperature and // a wind. if (!wind_valid or !sat_valid) return 0; // A field flagged invalid must be zero. if (!pressure_valid and pressure_raw != 0) return 0; if (!turbulence_valid and turbulence_raw != 0) return 0; if (!humidity_valid and humidity_raw != 0) return 0; var score: i32 = 0; const wind_speed: f32 = @floatFromInt(wind_speed_raw); const wind_dir: f32 = @floatCast(@as(f64, @floatFromInt(wind_dir_raw)) * (180.0 / 256.0)); if (wind_speed_raw == 0) { score += 2; // possible, but uncommon } else if (wind_speed <= 250) { score += 19; } else return 0; var temperature: f32 = @floatCast(@as(f64, @floatFromInt(sat_raw)) * 0.25); if (sat_sign) temperature -= 128; if (temperature == 0) { score += 2; // possible, but uncommon } else if (temperature >= -80 and temperature <= 60) { score += 11; } else return 0; var pressure: f32 = 0; if (pressure_valid) { pressure = @floatFromInt(pressure_raw); if (pressure >= 25 and pressure <= 1100) score += 12 else return 0; } else { score += 1; } var turbulence: message.Hazard = .nil; if (turbulence_valid) { turbulence = @enumFromInt(turbulence_raw); score += 3; } else { score += 1; } var humidity: f32 = 0; if (humidity_valid) { humidity = @floatCast(@as(f64, @floatFromInt(humidity_raw)) * (100.0 / 64.0)); score += 7; } else { score += 1; } // A BDS1,7 capability report can look exactly like a DME/DME-sourced // MRAR: its extended-squitter capability bits land on the source field // and read as 3, its ES-velocity bit lands on the wind status flag, its // heading/speed bit on the temperature status flag, and the rest is // zeros. Score that combination as a last resort rather than a match. if (source == @intFromEnum(message.MrarSource.dme_dme) and score > 0) score = 1; if (store) { mm.commb_format = .mrar; mm.meteorology.source = @enumFromInt(source); mm.meteorology.wind = .{ .speed = wind_speed, .direction = wind_dir }; mm.meteorology.temperature = temperature; if (pressure_valid) mm.meteorology.pressure = pressure; if (turbulence_valid) mm.meteorology.turbulence = turbulence; if (humidity_valid) mm.meteorology.humidity = humidity; } return score; } /// BDS0,5 extended squitter airborne position, which some transponders will /// hand over as a Comm-B reply. /// /// The position is not used — a squitter that arrives this way has been /// through a path nothing verifies. What the decoder is for is recognising /// the register at all, so that it does not get mistaken for a BDS4,4, which /// it otherwise can be. fn decodeBds05(mm: *Message, store: bool) i32 { // Recognition works by matching the altitude in the position against the // altitude in the surrounding reply, so it needs a DF20, which carries // one, rather than a DF21, which carries a squawk instead. if (!mm.format.is(20)) return 0; const msg = &mm.raw.mb; // Only the type codes that would be an airborne position with a // barometric altitude. const typecode = bits.get(msg, 1, 5); if (typecode < 9 or typecode > 18) return 0; // The UTC synchronisation bit is almost never set. if (bits.flag(msg, 21)) return 0; const ac12 = bits.get(msg, 9, 20); if (ac12 == 0) return 0; // Widen the 12-bit altitude to the 13-bit form by inserting the metric // bit as zero, then check it against the reply's own altitude field. const ac13 = ((ac12 & 0x0fc0) << 1) | (ac12 & 0x003f); if (mm.raw.ac != ac13) return 0; if (bits.get(msg, 23, 39) == 0 or bits.get(msg, 40, 56) == 0) return 0; if (store) mm.commb_format = .airborne_position; // High enough to beat everything else: a matching altitude is strong // evidence, and nothing else scores this well. return 100; } const testing = std.testing; fn messageWithMb(mb: [7]u8) Message { var mm: Message = .empty; mm.format = .{ .mode_s = 20 }; mm.raw.mb = mb; return mm; } test "an all-zero reply is an empty response" { var mm = messageWithMb(@splat(0)); decode(&mm); try testing.expectEqual(message.CommBFormat.empty_response, mm.commb_format); } test "the 40/50/60-then-zeros replies are empty responses too" { for ([_]u8{ 0x40, 0x50, 0x60 }) |first| { var mm = messageWithMb(.{ first, 0, 0, 0, 0, 0, 0 }); decode(&mm); try testing.expectEqual(message.CommBFormat.empty_response, mm.commb_format); } } test "a callsign reply decodes as BDS2,0" { // 0x20 then the same six-bit packing an extended squitter uses. var mm = messageWithMb(.{ 0x20, 0x2c, 0xc3, 0x71, 0xc3, 0x2c, 0xe0 }); decode(&mm); try testing.expectEqual(message.CommBFormat.aircraft_ident, mm.commb_format); try testing.expectEqualStrings("KLM1023 ", &mm.callsign.?); } test "a BDS2,0 of all padding is recognised but yields no callsign" { var mm = messageWithMb(.{ 0x20, 0, 0, 0, 0, 0, 0 }); decode(&mm); try testing.expectEqual(message.CommBFormat.aircraft_ident, mm.commb_format); try testing.expectEqual(@as(?[8]u8, null), mm.callsign); } test "a reply that needed correcting is not guessed at" { var mm = messageWithMb(.{ 0x20, 0x2c, 0xc3, 0x71, 0xc3, 0x2c, 0xe0 }); mm.corrected_bits = 1; decode(&mm); try testing.expectEqual(message.CommBFormat.not_decoded, mm.commb_format); try testing.expectEqual(@as(?[8]u8, null), mm.callsign); } test "a reply with a downlink request set is not guessed at" { var mm = messageWithMb(.{ 0x20, 0x2c, 0xc3, 0x71, 0xc3, 0x2c, 0xe0 }); mm.raw.dr = 1; decode(&mm); try testing.expectEqual(message.CommBFormat.not_decoded, mm.commb_format); } test "round altitudes" { try testing.expect(isRoundAltitude(10000)); try testing.expect(isRoundAltitude(10500)); // Within the sixteen-foot resolution of the field, either side. try testing.expect(isRoundAltitude(10496)); try testing.expect(isRoundAltitude(10512)); try testing.expect(!isRoundAltitude(10256)); }