// 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 //! Turning 56 or 112 bits into a `Message`. //! //! The work happens in three stages, and the order matters. First the frame //! is *corrected*: the CRC is computed at both lengths and, if it fails, the //! syndrome tables are consulted for a bit pattern that would rescue it — //! including patterns that change the downlink format itself, since the field //! that says how to read the frame is as corruptible as the rest of it. //! Second it is *scored*, because a receiver hears each transmission several //! times over and something has to choose between the copies; the score is a //! judgement about how much the frame can be believed, not how strong it was. //! Only then is it *decoded* into fields. //! //! Correction is where the risk lies. Most downlink formats have no usable //! CRC at all — the transponder overlays the aircraft's address on the parity //! field, so a receiver that does not know the address cannot check the //! parity, and one that does not know the parity cannot recover the address. //! Such a frame is accepted only if the address it implies belongs to an //! aircraft heard from recently, which is what `icao_filter.Filter` is for. //! Without that check, noise decodes into a sky full of aircraft. const std = @import("std"); const bits = @import("bits.zig"); const ais = @import("ais.zig"); const comm_b = @import("comm_b.zig"); const cpr = @import("cpr.zig"); const crc = @import("crc.zig"); const icao_filter = @import("icao_filter.zig"); const message = @import("message.zig"); const mode_ac = @import("mode_ac.zig"); const modes = @import("modes.zig"); const Message = message.Message; const ScoreRank = Message.ScoreRank; /// How the decoder should behave. pub const Options = struct { /// How many bit errors to try to correct. Off by default, as upstream /// has it: a corrected frame is a guess, and a receiver feeding an /// aggregator should be forwarding what it heard. fix_bits: crc.FixBits = .none, /// Whether to attempt corrections to the downlink format field as well as /// to the body. Correcting the format is much more expensive, because a /// frame that looks like an unreadable format has to be checked at both /// lengths in case it is a damaged DF11, DF17 or DF18. fix_df: bool = true, /// Whether to decode the Comm-D extended length messages, DF24 to DF31. /// Off by default: they carry no address of their own and nothing /// downstream uses them, so they are mostly a way for noise to get in. enable_df24: bool = false, }; /// A Mode S decoder: the tables and state that decoding a frame needs. /// /// The syndrome tables are expensive to build and the address filter is /// accumulated history, so both live here rather than being rebuilt per /// frame. pub const Decoder = struct { options: Options, /// The CRC syndrome tables, sized by `options.fix_bits`. crc_table: crc.Table, /// Which aircraft have been heard from recently. filter: icao_filter.Filter, /// How many position messages were dropped by the zero-position filter in /// `decodeAirbornePosition`. Collected here and reported by the stats. cpr_filtered: u64 = 0, pub fn init(gpa: std.mem.Allocator, options: Options) std.mem.Allocator.Error!Decoder { return .{ .options = options, .crc_table = try .init(gpa, options.fix_bits), .filter = .init, }; } pub fn deinit(self: *Decoder, gpa: std.mem.Allocator) void { self.crc_table.deinit(gpa); self.* = undefined; } /// Which correction table applies, given whether the downlink format /// itself may be corrected. fn dfFixBits(self: *const Decoder) u2 { if (!self.options.fix_df) return 0; return switch (self.options.fix_bits) { .none => 0, .one => 1, .two => 2, }; } }; /// Why a frame could not be decoded. pub const DecodeError = error{ /// The frame scored below `unknown_threshold`: not worth keeping. Implausible, /// The frame scored below `accept_threshold`, or its downlink format has /// no CRC handling at all. Worth counting, not worth acting on. Unacceptable, }; /// The 24-bit downlink formats that could become a DF11 after correcting up /// to *n* bits, as a bitset over the format value. /// /// Correcting a frame means computing a CRC over it, which is not free, and /// most frames are noise. These sets let a frame whose format could not /// possibly become a DF11/17/18 skip the CRC entirely. Generated by /// upstream's `tools/df-correction-arrays.py`. const df_correctable_short = [crc.max_bit_errors + 1]u32{ 0x00000800, 0x08008e08, 0x08008e08 }; /// The same, for formats that could become a DF17 or DF18. const df_correctable_long = [crc.max_bit_errors + 1]u32{ 0x00060000, 0x066f0006, 0x6fff066f }; /// What correcting a frame produced. const Correction = struct { /// The frame with any corrections applied. msg: [modes.max_message_bytes]u8, /// How many bits were flipped, or null if the frame could not be turned /// into a DF11, DF17 or DF18 at all — which is not itself a failure, as /// most downlink formats never could be. corrections: ?u8, /// The 56-bit syndrome, if it was worth computing. short_syndrome: ?u24, /// The 112-bit syndrome, if it was worth computing. long_syndrome: ?u24, }; /// Whether a frame's format is one of the long ones that carry a checkable /// parity/interrogator field. fn isLongParityFormat(msg: []const u8) bool { const df = bits.get(msg, 1, 5); return df == 17 or df == 18; } /// The same for the short one. DF11's parity carries the interrogator /// identity in its low seven bits, which is why only the top seventeen are /// checked; this assumes an interrogator identity of zero. fn isShortParityFormat(msg: []const u8) bool { return bits.get(msg, 1, 5) == 11; } /// Apply whatever corrections turn `in` into a valid DF11, DF17 or DF18, if /// any do. fn correctMessage(decoder: *const Decoder, in: []const u8) Correction { var result: Correction = .{ .msg = undefined, .corrections = null, .short_syndrome = null, .long_syndrome = null, }; const df_bit = @as(u32, 1) << @intCast(bits.get(in, 1, 5)); const fix_df_bits = decoder.dfFixBits(); var long_info: ?crc.ErrorInfo = null; if (df_correctable_long[fix_df_bits] & df_bit != 0) { const syndrome = crc.checksum(in[0..modes.max_message_bytes]); result.long_syndrome = syndrome; if (isLongParityFormat(in) and syndrome == 0) { @memcpy(&result.msg, in[0..modes.max_message_bytes]); result.corrections = 0; return result; } long_info = decoder.crc_table.diagnose(syndrome, .long); } var short_info: ?crc.ErrorInfo = null; if (df_correctable_short[fix_df_bits] & df_bit != 0) { const syndrome = crc.checksum(in[0..7]); result.short_syndrome = syndrome; if (isShortParityFormat(in) and syndrome & 0xffff80 == 0) { @memcpy(&result.msg, in[0..modes.max_message_bytes]); result.corrections = 0; return result; } short_info = decoder.crc_table.diagnose(syndrome, .short); } // A damaged DF11/17/18, or a format that has no full CRC to begin with. // Where both lengths offer a correction, prefer the one that flips fewer // bits, and the long one if they flip the same number. const long_errors: u16 = if (long_info) |info| info.error_count else 999; const short_errors: u16 = if (short_info) |info| info.error_count else 999; if (long_info) |info| { if (long_errors <= short_errors) { @memcpy(&result.msg, in[0..modes.max_message_bytes]); info.apply(&result.msg); if (isLongParityFormat(&result.msg)) { result.corrections = info.error_count; return result; } } } // Two-bit corrections of a DF11 are not attempted: several two-bit // patterns produce a syndrome whose low seven bits are zero, which is // exactly what a valid DF11 with a non-zero interrogator identity looks // like, so there is no way to tell a correction from an interrogation. if (short_info) |info| { if (short_errors == 1) { @memcpy(&result.msg, in[0..modes.max_message_bytes]); info.apply(result.msg[0..7]); if (isShortParityFormat(&result.msg)) { result.corrections = info.error_count; return result; } } } if (long_info) |info| { if (long_errors > short_errors) { @memcpy(&result.msg, in[0..modes.max_message_bytes]); info.apply(&result.msg); if (isLongParityFormat(&result.msg)) { result.corrections = info.error_count; return result; } } } @memcpy(&result.msg, in[0..modes.max_message_bytes]); return result; } /// How plausible a frame looks. See `Message.ScoreRank` for what the ranking /// means and why it is an order rather than a number. pub fn score(decoder: *const Decoder, uncorrected: []const u8) ScoreRank { // A frame of all zeros parses as a valid DF0, and noise produces them // constantly. if (std.mem.allEqual(u8, uncorrected[0..7], 0)) return .all_zeros; const correction = correctMessage(decoder, uncorrected); const msg = &correction.msg; const df: u5 = @intCast(bits.get(msg, 1, 5)); switch (df) { // Address/parity formats: the "address" is whatever the CRC comes out // as, so the only evidence that the frame is real is that the address // belongs to an aircraft that has been heard from. 0, 4, 5 => { const syndrome = correction.short_syndrome orelse crc.checksum(msg[0..7]); return if (decoder.filter.contains(syndrome)) .unreliable_known else .unreliable_unknown; }, 16, 20, 21 => { const syndrome = correction.long_syndrome orelse crc.checksum(msg); return if (decoder.filter.contains(syndrome)) .unreliable_known else .unreliable_unknown; }, 24...31 => { if (!decoder.options.enable_df24) return .uncorrectable; const syndrome = correction.long_syndrome orelse crc.checksum(msg); return if (decoder.filter.contains(syndrome)) .unreliable_known else .unreliable_unknown; }, 11 => { const address = bits.get(msg, 9, 32); const syndrome = correction.short_syndrome orelse crc.checksum(msg[0..7]); const acquisition = syndrome & 0x7f == 0; const known = decoder.filter.contains(address); return switch (correction.corrections orelse return .uncorrectable) { 0 => if (acquisition) (if (known) .df11_acq_known else .df11_acq_unknown) else (if (known) .df11_iid_known else .df11_iid_unknown), 1 => if (acquisition) (if (known) .df11_acq_1error_known else .df11_acq_1error_unknown) else (if (known) .df11_iid_1error_known else .df11_iid_1error_unknown), else => .uncorrectable, }; }, 17 => { const known = decoder.filter.contains(bits.get(msg, 9, 32)); return switch (correction.corrections orelse return .uncorrectable) { 0 => if (known) .df17_known else .df17_unknown, 1 => if (known) .df17_1error_known else .df17_1error_unknown, 2 => if (known) .df17_2error_known else .df17_2error_unknown, else => .uncorrectable, }; }, 18 => { // Only previous DF18 activity counts: a DF18 and a DF11 that name // the same address are different transmitters that happen to // share a number. const known = decoder.filter.contains(bits.get(msg, 9, 32) | icao_filter.Filter.adsb_nt); return switch (correction.corrections orelse return .uncorrectable) { 0 => if (known) .df18_known else .df18_unknown, 1 => if (known) .df18_1error_known else .df18_1error_unknown, 2 => if (known) .df18_2error_known else .df18_2error_unknown, else => .uncorrectable, }; }, else => return .unknown_df, } } /// Decode a frame into `mm`. /// /// `mm` is filled in rather than returned so that the caller can set the /// fields that do not come from the frame — the timestamps, the signal level, /// whether it arrived over the network — before decoding, since some of them /// change the outcome. pub fn decode(decoder: *Decoder, mm: *Message, in: []const u8) DecodeError!void { // A message off the network arrives unscored. const rank = mm.score orelse blk: { const rank = score(decoder, in); mm.score = rank; break :blk rank; }; if (!rank.isPlausible()) return error.Implausible; if (!rank.isAcceptable()) return error.Unacceptable; // Keep the frame exactly as received, so that what gets forwarded to // other receivers is what arrived rather than our guess at it. @memcpy(&mm.verbatim, in[0..modes.max_message_bytes]); const correction = correctMessage(decoder, in); mm.msg = correction.msg; const msg = &mm.msg; // The format decides everything else, so it comes first. var df: u5 = @intCast(bits.get(msg, 1, 5)); const length = modes.MessageLength.fromDownlinkFormat(df); mm.len = length.bytes(); mm.crc = switch (length) { .long => correction.long_syndrome orelse crc.checksum(msg), .short => correction.short_syndrome orelse crc.checksum(msg[0..7]), }; mm.corrected_bits = correction.corrections orelse 0; mm.address = 0; switch (df) { // Address/parity formats. The address cannot be checked, only // inferred, so nothing here is reliable. 0, 4, 5, 16 => { mm.source = .mode_s; mm.address = mm.crc; mm.reliable = false; }, // All-call reply. The parity carries the interrogator's identity in // its low seven bits, which we cannot know — but the top seventeen // still check out, so errors are detectable there. 11 => { mm.raw.iid = mm.crc & 0x7f; mm.source = .mode_s_checked; mm.reliable = mm.raw.iid == 0 and mm.corrected_bits == 0; }, // Extended squitters, which are specified to leave the interrogator // identity at zero, so the CRC is fully checkable. 17, 18 => { // TIS-B decoding may override this. mm.source = .adsb; mm.reliable = mm.corrected_bits == 0; }, // Comm-B replies use either address/parity or data parity, where the // requested register number is also folded into the top byte. So // neither the CRC nor the address can be trusted. 20, 21 => { mm.source = .mode_s; mm.address = mm.crc; mm.reliable = false; }, // Comm-D extended length messages carry data in some of the format // bits themselves. Collapse them to one format, since the difference // is payload rather than meaning. 24...31 => { df = 24; mm.source = .mode_s; mm.address = mm.crc; mm.reliable = false; }, // Nothing else has a CRC arrangement we know how to handle. else => return error.Unacceptable, } mm.format = .{ .mode_s = df }; // AA, address announced. if (df == 11 or df == 17 or df == 18) { mm.raw.aa = bits.get(msg, 9, 32); mm.address = mm.raw.aa; } // AC, altitude code. if (df == 0 or df == 4 or df == 16 or df == 20) { mm.raw.ac = bits.get(msg, 20, 32); // Zero is "no altitude", not an altitude of zero. if (mm.raw.ac != 0) mm.altitude_baro = decodeAc13Field(@intCast(mm.raw.ac)); } // CA, capability. if (df == 11 or df == 17) { mm.raw.ca = bits.get(msg, 6, 8); mm.airground = switch (mm.raw.ca) { 4 => .ground, 5 => .airborne, 0, 6, 7 => .uncertain, else => mm.airground, }; } // CC, cross-link capability. if (df == 0) mm.raw.cc = bits.get1(msg, 7); // CF, control field. if (df == 18) mm.raw.cf = bits.get(msg, 6, 8); // DR, downlink request. if (df == 4 or df == 5 or df == 20 or df == 21) mm.raw.dr = bits.get(msg, 9, 13); // FS, flight status: the air/ground state plus the alert and ident bits. if (df == 4 or df == 5 or df == 20 or df == 21) { mm.raw.fs = bits.get(msg, 6, 8); switch (mm.raw.fs) { 0 => { mm.airground = .uncertain; mm.alert = false; mm.spi = false; }, 1 => { mm.airground = .ground; mm.alert = false; mm.spi = false; }, 2 => { mm.airground = .uncertain; mm.alert = true; mm.spi = false; }, 3 => { mm.airground = .ground; mm.alert = true; mm.spi = false; }, 4 => { mm.airground = .uncertain; mm.alert = true; mm.spi = true; }, 5 => { mm.airground = .uncertain; mm.alert = false; mm.spi = true; }, // 6 and 7 are reserved: the frame says nothing about either. else => {}, } } // ID, the Gillham-coded squawk. if (df == 5 or df == 21) { mm.raw.id = bits.get(msg, 20, 32); if (mm.raw.id != 0) mm.squawk = decodeId13Field(@intCast(mm.raw.id)); } // KE and ND, the Comm-D segment control fields. if (df == 24) { mm.raw.ke = bits.get1(msg, 4); mm.raw.nd = bits.get(msg, 5, 8); @memcpy(&mm.raw.md, msg[1..11]); } // MB, the Comm-B payload. // // The Comm-B decoder reads `raw.dr` to decide whether the reply is worth // guessing at, so the downlink request above has to be read first. It // reads `raw.um` for the same purpose, and that is set *after* this call // rather than before — so the utility-message half of the check never // fires. That is upstream's ordering, and reproducing it matters: a // reply with a non-zero utility message really does get its registers // guessed at, and changing that would change the output. if (df == 20 or df == 21) { @memcpy(&mm.raw.mb, msg[4..11]); comm_b.decode(mm); } // UM, utility message. if (df == 4 or df == 5 or df == 20 or df == 21) mm.raw.um = bits.get(msg, 14, 19); // ME, the extended squitter payload. if (df == 17 or df == 18) { @memcpy(&mm.raw.me, msg[4..11]); decodeExtendedSquitter(decoder, mm); } // MV, the ACAS payload. if (df == 16) @memcpy(&mm.raw.mv, msg[4..11]); // RI and SL, the ACAS reply information and sensitivity level. if (df == 0 or df == 16) { mm.raw.ri = bits.get(msg, 14, 17); mm.raw.sl = bits.get(msg, 9, 11); } // VS, vertical status. if (df == 0 or df == 16) { mm.raw.vs = bits.get1(msg, 6); mm.airground = if (mm.raw.vs != 0) .ground else .uncertain; } // Remember this aircraft, so that the address-overlaid formats it sends // later can be believed. Only uncorrected frames vouch for an address: a // corrected one could have been corrected into the wrong aircraft. if (mm.corrected_bits == 0) { if (df == 17 or (df == 11 and mm.raw.iid == 0)) { _ = decoder.filter.add(mm.address); } else if (df == 18) { _ = decoder.filter.add(mm.address | icao_filter.Filter.adsb_nt); } } // A multilateration result is not really a received message at all, and // overrides whatever the frame claimed about its own provenance. if (mm.isMlat()) mm.source = .mlat; } /// Decode a Mode A/C reply into `mm`. /// /// A Mode A/C reply has no address, no format field and no error detection. /// What is built here is a Mode S-shaped message carrying what little the /// twelve pulses said, so that the rest of the program has one message type /// to deal with rather than two. pub fn decodeModeAC(mm: *Message, mode_a: u16) void { mm.source = .mode_ac; mm.address_type = .mode_a; mm.format = .mode_ac; mm.len = 2; mm.msg[0] = @intCast(mode_a >> 8); mm.msg[1] = @truncate(mode_a); mm.verbatim[0] = mm.msg[0]; mm.verbatim[1] = mm.msg[1]; // Fabricate an address from the squawk, less the ident bit, and mark it // as not being a real ICAO address. mm.address = (mode_a & 0x0000ff7f) | message.non_icao_address; mm.squawk = mode_a & 0x7777; mm.spi = mode_a & 0x0080 != 0; // The same twelve pulses are an altitude if the interrogation was Mode C // rather than Mode A — but the ident pulse only exists in a Mode A reply, // so a reply carrying it cannot be an altitude. // // A deliberate departure from upstream, and the only one in the decoder. // `demodulate2400AC` clears its message once per block of samples rather // than once per reply, where the Mode S loop clears it per message, and // this function only ever *sets* the altitude — so a reply whose code // carries no altitude keeps whatever the previous reply in that block // had. On forty-five seconds of real traffic that put a wrong altitude on // nineteen of the hundred and eighty-three Mode A/C replies that reported // one, each belonging to a different aircraft. Building a fresh message // per reply, as this does, is the whole of the fix. mm.altitude_baro = null; if (!mm.spi.?) { if (mode_ac.toAltitude(mode_a)) |hundreds| { mm.altitude_baro = .{ .value = @as(i32, hundreds) * 100, .unit = .feet }; } } mm.corrected_bits = 0; } test "a Mode A/C reply with no altitude does not inherit the last one's" { // Upstream reuses one message struct for every reply in a block, so a // code that decodes to no altitude shows the previous reply's. 0x4120 is // 3000 feet; 0x1000 is a valid squawk with no Mode C reading at all. var mm: Message = .empty; decodeModeAC(&mm, 0x4120); try testing.expectEqual(@as(i32, 3000), mm.altitude_baro.?.value); // The same message struct again, as upstream would reuse it. decodeModeAC(&mm, 0x1000); try testing.expectEqual(@as(?message.Altitude, null), mm.altitude_baro); try testing.expectEqual(@as(u16, 0x1000), mm.squawk.?); } /// Unpack the thirteen-bit identity field into the hex-per-octal-digit form /// everything else uses. /// /// The pulses arrive interleaved — `C1 A1 C2 A2 C4 A4 X B1 D1 B2 D2 B4 D4` — /// so each of the four octal digits has to be gathered from every third bit. fn decodeId13Field(id13: u13) u16 { var squawk: u16 = 0; if (id13 & 0x1000 != 0) squawk |= 0x0010; // C1 if (id13 & 0x0800 != 0) squawk |= 0x1000; // A1 if (id13 & 0x0400 != 0) squawk |= 0x0020; // C2 if (id13 & 0x0200 != 0) squawk |= 0x2000; // A2 if (id13 & 0x0100 != 0) squawk |= 0x0040; // C4 if (id13 & 0x0080 != 0) squawk |= 0x4000; // A4 // Bit 0x0040 is X (unused) in an identity field and M in an altitude one. if (id13 & 0x0020 != 0) squawk |= 0x0100; // B1 if (id13 & 0x0010 != 0) squawk |= 0x0001; // D1, or Q in an altitude field if (id13 & 0x0008 != 0) squawk |= 0x0200; // B2 if (id13 & 0x0004 != 0) squawk |= 0x0002; // D2 if (id13 & 0x0002 != 0) squawk |= 0x0400; // B4 if (id13 & 0x0001 != 0) squawk |= 0x0004; // D4 return squawk; } /// Decode the thirteen-bit altitude field used by DF0, DF4, DF16 and DF20. /// /// Two encodings share the field, chosen by the Q bit: a plain count of /// 25-foot steps, or the Gilham code inherited from Mode C. The M bit selects /// metres, which nothing in service uses and which is therefore not decoded. fn decodeAc13Field(ac13: u13) ?message.Altitude { const metric = ac13 & 0x0040 != 0; const q_bit = ac13 & 0x0010 != 0; if (metric) return null; if (q_bit) { // An eleven-bit count of 25-foot steps, with the Q and M bits removed // from the middle of it. const n = ((ac13 & 0x1f80) >> 2) | ((ac13 & 0x0020) >> 1) | (ac13 & 0x000f); return .{ .value = @as(i32, n) * 25 - 1000, .unit = .feet }; } const hundreds = mode_ac.toAltitude(decodeId13Field(ac13)) orelse return null; return .{ .value = @as(i32, hundreds) * 100, .unit = .feet }; } /// Decode the twelve-bit altitude field used by the extended squitter, which /// is the thirteen-bit one with the metric bit left out. fn decodeAc12Field(ac12: u12) ?message.Altitude { const q_bit = ac12 & 0x10 != 0; if (q_bit) { const n = ((ac12 & 0x0fe0) >> 1) | (ac12 & 0x000f); return .{ .value = @as(i32, n) * 25 - 1000, .unit = .feet }; } // Put the metric bit back, as a zero, to make a thirteen-bit field. const ac13: u13 = ((@as(u13, ac12) & 0x0fc0) << 1) | (ac12 & 0x003f); const hundreds = mode_ac.toAltitude(decodeId13Field(ac13)) orelse return null; return .{ .value = @as(i32, hundreds) * 100, .unit = .feet }; } /// Decode the seven-bit surface movement field as ADS-B version 2 defines it. /// /// The scale is piecewise: fine steps at taxi speeds where a knot matters and /// coarse ones above, so each code is a range rather than a value. What is /// returned is the middle of the range. fn decodeMovementV2(movement: u7) f32 { const m: f64 = @floatFromInt(movement); // Codes 0 and 125 to 127 are not speeds; callers filter them out first, // and anything that slips through reads as stopped. if (movement >= 125) return 0; if (movement == 124) return 180; // above 175 knots, so pick a number if (movement >= 109) return @floatCast(100 + (m - 109 + 0.5) * 5); if (movement >= 94) return @floatCast(70 + (m - 94 + 0.5) * 2); if (movement >= 39) return @floatCast(15 + (m - 39 + 0.5) * 1); if (movement >= 13) return @floatCast(2 + (m - 13 + 0.5) * 0.50); if (movement >= 9) return @floatCast(1 + (m - 9 + 0.5) * 0.25); if (movement >= 3) return @floatCast(0.125 + (m - 3 + 0.5) * 0.875 / 6); if (movement >= 2) return 0.0625; return 0; // 1 is stopped, 0 is no data } /// The same field as ADS-B version 0 defines it, which differs only at the /// bottom of the scale. fn decodeMovementV0(movement: u7) f32 { const m: f64 = @floatFromInt(movement); if (movement >= 125) return 0; if (movement == 124) return 180; if (movement >= 109) return @floatCast(100 + (m - 109 + 0.5) * 5); if (movement >= 94) return @floatCast(70 + (m - 94 + 0.5) * 2); if (movement >= 39) return @floatCast(15 + (m - 39 + 0.5) * 1); if (movement >= 13) return @floatCast(2 + (m - 13 + 0.5) * 0.50); if (movement >= 9) return @floatCast(1 + (m - 9 + 0.5) * 0.25); if (movement >= 2) return @floatCast(0.125 + (m - 2 + 0.5) * 0.125); return 0; } /// Mark the address as something other than an ICAO aircraft address. /// /// TIS-B and ADS-R messages carry an IMF bit saying that the address field /// holds something else — a Mode A code and a track file number, or an /// anonymous identifier — and the address type has to be demoted to match. fn setImf(mm: *Message) void { mm.address |= message.non_icao_address; mm.address_type = switch (mm.address_type) { // Should not happen, but demote rather than lie about it. .adsb_icao, .adsb_icao_nt => .adsb_other, .tisb_icao => .tisb_trackfile, .adsr_icao => .adsr_other, else => mm.address_type, }; } /// Decode the 56-bit extended squitter payload. fn decodeExtendedSquitter(decoder: *Decoder, mm: *Message) void { const me = &mm.raw.me; mm.metype = @intCast(bits.get(me, 1, 5)); // A DF18 is not necessarily from an aircraft: the control field says who // is talking and, for the rebroadcast formats, whether the address field // holds an address at all. var check_imf = false; if (mm.format.is(18)) { switch (mm.raw.cf) { // ADS-B from something that is not a transponder, with a real // ICAO address. 0 => mm.address_type = .adsb_icao_nt, // ADS-B with an anonymous, ground vehicle or fixed obstruction // address. 1 => { mm.address_type = .adsb_other; mm.address |= message.non_icao_address; }, // Fine TIS-B: ground radar rebroadcasting a target it sees. 2 => { mm.source = .tisb; mm.address_type = .tisb_icao; check_imf = true; }, // Coarse TIS-B position and velocity, which uses a different // layout that is not decoded here — only the IMF bit is read. 3 => { mm.source = .tisb; mm.address_type = .tisb_icao; if (bits.flag(me, 1)) setImf(mm); return; }, // Fine TIS-B with a non-ICAO address. 5 => { mm.address_type = .tisb_other; mm.source = .tisb; mm.address |= message.non_icao_address; }, // ADS-R: a rebroadcast of an ADS-B message that arrived over // another data link. 6 => { mm.address_type = .adsr_icao; mm.source = .adsr; check_imf = true; }, else => { mm.address_type = .unknown; mm.address |= message.non_icao_address; return; }, } } switch (mm.metype) { 1...4 => decodeIdentAndCategory(mm), 5...8 => decodeSurfacePosition(mm, check_imf), 0, 9...18, 20...22 => decodeAirbornePosition(decoder, mm, check_imf), 19 => decodeAirborneVelocity(mm, check_imf), 23 => decodeTestMessage(mm), 24 => {}, // reserved for surface system status 28 => decodeAircraftStatus(mm, check_imf), 29 => decodeTargetStatus(mm, check_imf), 30 => {}, // aircraft operational coordination 31 => decodeOperationalStatus(mm, check_imf), // A type nothing defines. The frame may still have a good CRC, but // there is no reason to believe it. else => mm.reliable = false, } } /// Type 1-4: the callsign and the wake turbulence category. fn decodeIdentAndCategory(mm: *Message) void { const me = &mm.raw.me; mm.mesub = @intCast(bits.get(me, 6, 8)); const callsign = ais.decodeCallsign(me, 9); // The six-bit alphabet has 64 codes and a callsign may only use 37 of // them, so anything else means the frame is not what it claims to be. for (callsign) |character| { switch (character) { 'A'...'Z', '0'...'9', ' ' => {}, else => break, } } else { mm.callsign = callsign; } // The category is the type and subtype together, as a letter-and-digit // pair packed into one byte: type 4 subtype 1 is A1, type 1 subtype 1 is // D1. mm.category = (@as(u8, 0x0e - mm.metype) << 4) | mm.mesub; } /// Type 19: velocity over the ground, or airspeed and heading. fn decodeAirborneVelocity(mm: *Message, check_imf: bool) void { const me = &mm.raw.me; mm.mesub = @intCast(bits.get(me, 6, 8)); if (mm.mesub < 1 or mm.mesub > 4) return; if (check_imf and bits.flag(me, 9)) setImf(mm); // NACv in version 2, NUCr in version 0; the encodings coincide. mm.accuracy.nac_v = @intCast(bits.get(me, 11, 13)); switch (mm.mesub) { // Ground speed, as east/west and north/south components. Subtype 2 is // the same in units of four knots, for aircraft fast enough that the // one-knot field would overflow. 1, 2 => { const ew_raw = bits.get(me, 15, 24); const ns_raw = bits.get(me, 26, 35); if (ew_raw != 0 and ns_raw != 0) { const scale: i32 = if (mm.mesub == 2) 4 else 1; const ew: i32 = @as(i32, @intCast(ew_raw - 1)) * (if (bits.flag(me, 14)) @as(i32, -1) else 1) * scale; const ns: i32 = @as(i32, @intCast(ns_raw - 1)) * (if (bits.flag(me, 25)) @as(i32, -1) else 1) * scale; const squared: f64 = @floatFromInt(ns * ns + ew * ew); const speed: f32 = @sqrt(@as(f32, @floatCast(squared + 0.5))); mm.gs = .exact(speed); if (speed > 0) { var track: f32 = @floatCast(std.math.atan2( @as(f64, @floatFromInt(ew)), @as(f64, @floatFromInt(ns)), ) * 180.0 / std.math.pi); if (track < 0) track = @floatCast(@as(f64, track) + 360.0); mm.heading = .{ .degrees = track, .type = .ground_track }; } } }, // Airspeed and heading, for aircraft without a ground speed solution. 3, 4 => { if (bits.flag(me, 14)) { mm.heading = .{ .degrees = @floatCast(@as(f64, @floatFromInt(bits.get(me, 15, 24))) * 360.0 / 1024.0), .type = .magnetic_or_true, }; } const airspeed = bits.get(me, 26, 35); if (airspeed != 0) { const speed = (airspeed - 1) * (if (mm.mesub == 4) @as(u32, 4) else 1); if (bits.flag(me, 25)) mm.tas = speed else mm.ias = speed; } }, else => unreachable, } // Vertical rate, from either the altimeter or the satellite receiver. const vert_rate = bits.get(me, 38, 46); if (vert_rate != 0) { const rate = @as(i32, @intCast(vert_rate - 1)) * (if (bits.flag(me, 37)) @as(i32, -64) else 64); if (bits.flag(me, 36)) mm.baro_rate = rate else mm.geom_rate = rate; } // The difference between the two altitudes, which is how a geometric // altitude is recovered from a message that only carries a barometric // one. const raw_delta = bits.get(me, 50, 56); if (raw_delta != 0) { mm.geom_delta = @as(i32, @intCast(raw_delta - 1)) * (if (bits.flag(me, 49)) @as(i32, -25) else 25); } } /// Types 5-8: position and movement on the ground. fn decodeSurfacePosition(mm: *Message, check_imf: bool) void { const me = &mm.raw.me; mm.airground = .ground; // not a guess: this message only exists on the ground // Ground speed. The scale changed between ADS-B versions and the message // does not say which it is, so both readings are kept and the tracker // picks once it knows the aircraft's version. const movement = bits.get(me, 6, 12); if (movement > 0 and movement < 125) { const raw: u7 = @intCast(movement); const v0 = decodeMovementV0(raw); mm.gs = .{ .v0 = v0, .v2 = decodeMovementV2(raw), .selected = v0 }; } if (bits.flag(me, 13)) { mm.heading = .{ .degrees = @floatCast(@as(f64, @floatFromInt(bits.get(me, 14, 20))) * 360.0 / 128.0), .type = .track_or_heading, }; } if (check_imf and bits.flag(me, 21)) setImf(mm); mm.cpr = .{ .frame = if (bits.flag(me, 22)) .odd else .even, .type = .surface, .encoded = .{ .latitude = @intCast(bits.get(me, 23, 39)), .longitude = @intCast(bits.get(me, 40, 56)), }, }; } /// Types 0 and 9-22: position and altitude in the air. fn decodeAirbornePosition(decoder: *Decoder, mm: *Message, check_imf: bool) void { const me = &mm.raw.me; // Surveillance status: the alert and ident bits, packed into two bits // that cannot express every combination. switch (bits.get(me, 6, 7)) { 0 => { mm.alert = false; mm.spi = false; }, // A permanent or temporary alert overrides the ident state, so this // says nothing about whether the ident button was pressed. 1, 2 => mm.alert = true, 3 => { mm.alert = false; mm.spi = true; }, else => unreachable, } if (check_imf) { if (bits.flag(me, 8)) setImf(mm); } else { // NIC supplement B in version 2, the single antenna flag in earlier // versions. mm.accuracy.nic_b = @intCast(bits.get1(me, 8)); } const ac12: u12 = @intCast(bits.get(me, 9, 20)); // Type 0 is "no position information available". if (mm.metype != 0) { const latitude: u17 = @intCast(bits.get(me, 23, 39)); const longitude: u17 = @intCast(bits.get(me, 40, 56)); // A handful of aircraft emit a type 15 message with no altitude, a // zero longitude and the low twelve bits of latitude zero, alternating // with perfectly good type 14 reports. Off the coast of west Africa // is a real place and this is not it. if (ac12 == 0 and longitude == 0 and latitude & 0x0fff == 0 and mm.metype == 15) { decoder.cpr_filtered += 1; } else { mm.cpr = .{ .frame = if (bits.flag(me, 22)) .odd else .even, .type = .airborne, .encoded = .{ .latitude = latitude, .longitude = longitude }, }; } } // An aircraft reporting an altitude is not on the ground, whatever else // was said — but a message that already established the ground state is // not overridden by one. if (ac12 != 0 and mm.airground != .ground) { if (decodeAc12Field(ac12)) |altitude| { if (mm.airground == .invalid) mm.airground = .uncertain; // Types 20 to 22 report height above the ellipsoid rather than // pressure altitude. if (mm.metype >= 20 and mm.metype <= 22) { mm.altitude_geom = altitude; } else { mm.altitude_baro = altitude; } } } } /// Type 23: the test message, which subtype 7 uses to carry a squawk. fn decodeTestMessage(mm: *Message) void { const me = &mm.raw.me; mm.mesub = @intCast(bits.get(me, 6, 8)); if (mm.mesub == 7) { const id13 = bits.get(me, 9, 21); if (id13 != 0) mm.squawk = decodeId13Field(@intCast(id13)); } } /// Type 28: emergency and priority status. fn decodeAircraftStatus(mm: *Message, check_imf: bool) void { const me = &mm.raw.me; mm.mesub = @intCast(bits.get(me, 6, 8)); if (mm.mesub == 1) { mm.emergency = @enumFromInt(bits.get(me, 9, 11)); const id13 = bits.get(me, 12, 24); if (id13 != 0) mm.squawk = decodeId13Field(@intCast(id13)); if (check_imf and bits.flag(me, 56)) setImf(mm); } } /// Type 29: where the autopilot is taking the aircraft. /// /// This message changed shape between ADS-B version 1 and version 2 and the /// two are told apart by the subtype, which is unusually two bits wide here /// rather than three. fn decodeTargetStatus(mm: *Message, check_imf: bool) void { const me = &mm.raw.me; mm.mesub = @intCast(bits.get(me, 6, 7)); if (check_imf and bits.flag(me, 51)) setImf(mm); if (mm.mesub == 0 and bits.get1(me, 11) == 0) { decodeTargetStatusV1(mm, me); } else if (mm.mesub == 1) { decodeTargetStatusV2(mm, me); } } fn decodeTargetStatusV1(mm: *Message, me: *const [7]u8) void { mm.nav.altitude_source = switch (bits.get(me, 8, 9)) { 1 => .mcp, 2 => .aircraft, 3 => .fms, else => mm.nav.altitude_source, }; // The vertical mode says what the autopilot is doing about altitude, and // which mode that implies depends on where the target came from. switch (bits.get(me, 14, 15)) { 1 => { // acquiring var engaged = mm.nav.modes orelse message.NavModes.none; if (mm.nav.altitude_source == .fms) engaged.vnav = true else engaged.autopilot = true; mm.nav.modes = engaged; }, 2 => { // maintaining var engaged = mm.nav.modes orelse message.NavModes.none; switch (mm.nav.altitude_source) { .fms => engaged.vnav = true, .aircraft => engaged.alt_hold = true, else => engaged.autopilot = true, } mm.nav.modes = engaged; }, else => {}, } const altitude: i32 = -1000 + 100 * @as(i32, @intCast(bits.get(me, 16, 25))); switch (mm.nav.altitude_source) { .mcp => mm.nav.mcp_altitude = altitude, .fms => mm.nav.fms_altitude = altitude, else => {}, } const horizontal_source = bits.get(me, 26, 27); if (horizontal_source != 0) { mm.nav.heading = .{ .degrees = @floatFromInt(bits.get(me, 28, 36)), .type = if (bits.flag(me, 37)) .ground_track else .magnetic_or_true, }; } switch (bits.get(me, 38, 39)) { 1, 2 => { // acquiring or maintaining var engaged = mm.nav.modes orelse message.NavModes.none; if (horizontal_source == 3) engaged.lnav = true else engaged.autopilot = true; mm.nav.modes = engaged; }, else => {}, } mm.accuracy.nac_p = @intCast(bits.get(me, 40, 43)); mm.accuracy.nic_baro = @intCast(bits.get1(me, 44)); mm.accuracy.sil = @intCast(bits.get(me, 45, 46)); mm.accuracy.sil_type = .unknown; switch (bits.get(me, 52, 53)) { 1 => mm.nav.modes = mm.nav.modes orelse message.NavModes.none, // no TCAS 2, 3 => { var engaged = mm.nav.modes orelse message.NavModes.none; engaged.tcas = true; mm.nav.modes = engaged; }, // Assume TCAS is fitted, but do not let that alone make the mode // field meaningful. 0 => if (mm.nav.modes) |*engaged| { engaged.tcas = true; }, else => {}, } mm.emergency = @enumFromInt(bits.get(me, 54, 56)); } fn decodeTargetStatusV2(mm: *Message, me: *const [7]u8) void { const is_fms = bits.flag(me, 9); const alt_bits = bits.get(me, 10, 20); if (alt_bits != 0) { const altitude: i32 = @as(i32, @intCast(alt_bits - 1)) * 32; if (is_fms) mm.nav.fms_altitude = altitude else mm.nav.mcp_altitude = altitude; } const baro_bits = bits.get(me, 21, 29); if (baro_bits != 0) { mm.nav.qnh = @floatCast(800.0 + @as(f64, @floatFromInt(baro_bits - 1)) * 0.8); } if (bits.flag(me, 30)) { // Two's complement over -180 to +180, which for this field is the // same bit pattern as unsigned 0 to 360. mm.nav.heading = .{ .degrees = @floatCast(@as(f64, @floatFromInt(bits.get(me, 31, 39))) * 180.0 / 256.0), .type = .magnetic_or_true, }; } mm.accuracy.nac_p = @intCast(bits.get(me, 40, 43)); mm.accuracy.nic_baro = @intCast(bits.get1(me, 44)); mm.accuracy.sil = @intCast(bits.get(me, 45, 46)); mm.accuracy.sil_type = .unknown; if (bits.flag(me, 47)) { mm.nav.modes = .{ .autopilot = bits.flag(me, 48), .vnav = bits.flag(me, 49), .alt_hold = bits.flag(me, 50), // 51 is the IMF bit, read above. .approach = bits.flag(me, 52), .tcas = bits.flag(me, 53), .lnav = bits.flag(me, 54), }; } } /// Type 31: what equipment the aircraft has and which version of the standard /// it implements. /// /// This is the message that makes the others readable, since several fields /// elsewhere mean different things in different ADS-B versions. fn decodeOperationalStatus(mm: *Message, check_imf: bool) void { const me = &mm.raw.me; mm.mesub = @intCast(bits.get(me, 6, 8)); if (check_imf and bits.flag(me, 56)) setImf(mm); // Subtype 0 is the airborne report and subtype 1 the surface one; nothing // else is defined. if (mm.mesub != 0 and mm.mesub != 1) return; var status: message.OpStatus = .{ .version = @intCast(bits.get(me, 41, 43)) }; const airborne = mm.mesub == 0; switch (status.version) { 0 => { if (airborne and bits.get(me, 9, 10) == 0) { status.cc_acas = !bits.flag(me, 12); status.cc_cdti = bits.flag(me, 13); } }, 1 => { if (bits.get(me, 25, 26) == 0) { status.om_acas_ra = bits.flag(me, 27); status.om_ident = bits.flag(me, 28); status.om_atc = bits.flag(me, 29); } if (bits.get(me, 9, 10) == 0 and bits.get(me, 13, 14) == 0) { if (airborne) { status.cc_acas = !bits.flag(me, 11); status.cc_cdti = bits.flag(me, 12); status.cc_arv = bits.flag(me, 15); status.cc_ts = bits.flag(me, 16); status.cc_tc = @intCast(bits.get(me, 17, 18)); } else { status.cc_poa = bits.flag(me, 11); status.cc_cdti = bits.flag(me, 12); status.cc_b2_low = bits.flag(me, 15); status.cc_lw = @intCast(bits.get(me, 21, 24)); } } mm.accuracy.nic_a = @intCast(bits.get1(me, 44)); mm.accuracy.nac_p = @intCast(bits.get(me, 45, 48)); mm.accuracy.sil_type = .unknown; mm.accuracy.sil = @intCast(bits.get(me, 51, 52)); status.hrd = if (bits.flag(me, 54)) .magnetic_heading else .true_heading; if (airborne) { mm.accuracy.nic_baro = @intCast(bits.get1(me, 53)); } else { // DO-260B §2.2.3.2.7.2.12: with this bit clear a surface // movement report gives ground track, with it set the // aircraft's own heading. status.tah = if (bits.flag(me, 53)) status.hrd else .ground_track; } }, 2 => { if (bits.get(me, 25, 26) == 0) { status.om_acas_ra = bits.flag(me, 27); status.om_ident = bits.flag(me, 28); status.om_atc = bits.flag(me, 29); status.om_saf = bits.flag(me, 30); mm.accuracy.sda = @intCast(bits.get(me, 31, 32)); } if (bits.get(me, 9, 10) == 0) { if (airborne) { // Version 2 inverted the sense of this bit. status.cc_acas = bits.flag(me, 11); status.cc_1090_in = bits.flag(me, 12); status.cc_arv = bits.flag(me, 15); status.cc_ts = bits.flag(me, 16); status.cc_tc = @intCast(bits.get(me, 17, 18)); status.cc_uat_in = bits.flag(me, 19); } else { status.cc_poa = bits.flag(me, 11); status.cc_1090_in = bits.flag(me, 12); status.cc_b2_low = bits.flag(me, 15); status.cc_uat_in = bits.flag(me, 16); mm.accuracy.nac_v = @intCast(bits.get(me, 17, 19)); mm.accuracy.nic_c = @intCast(bits.get1(me, 20)); status.cc_lw = @intCast(bits.get(me, 21, 24)); status.cc_antenna_offset = @intCast(bits.get(me, 33, 40)); } } mm.accuracy.nic_a = @intCast(bits.get1(me, 44)); mm.accuracy.nac_p = @intCast(bits.get(me, 45, 48)); mm.accuracy.sil = @intCast(bits.get(me, 51, 52)); mm.accuracy.sil_type = if (bits.flag(me, 55)) .per_sample else .per_hour; status.hrd = if (bits.flag(me, 54)) .magnetic_heading else .true_heading; if (airborne) { mm.accuracy.gva = @intCast(bits.get(me, 49, 50)); mm.accuracy.nic_baro = @intCast(bits.get1(me, 53)); } else { status.tah = if (bits.flag(me, 53)) status.hrd else .ground_track; } }, // Versions 3 and up do not exist yet; the message is recorded as // valid but nothing is read out of it. else => {}, } mm.opstatus = status; } const testing = std.testing; /// A real DF17 airborne position from aircraft 40:62:1D, the even half of the /// pair used throughout the ADS-B literature as a worked example. const df17_position = [_]u8{ 0x8d, 0x40, 0x62, 0x1d, 0x58, 0xc3, 0x82, 0xd6, 0x90, 0xc8, 0xac, 0x28, 0x63, 0xa7 }; /// A real DF17 identification message from aircraft 48:40:D6. const df17_ident = [_]u8{ 0x8d, 0x48, 0x40, 0xd6, 0x20, 0x2c, 0xc3, 0x71, 0xc3, 0x2c, 0xe0, 0x57, 0x60, 0x98 }; fn testDecoder() !Decoder { return .init(testing.allocator, .{ .fix_bits = .one }); } test "a clean extended squitter decodes" { var decoder = try testDecoder(); defer decoder.deinit(testing.allocator); var mm: Message = .empty; try decode(&decoder, &mm, &df17_ident); try testing.expectEqual(@as(u5, 17), mm.format.mode_s); try testing.expectEqual(@as(u32, 0x4840d6), mm.address); try testing.expectEqual(@as(u24, 0), mm.crc); try testing.expectEqual(@as(u8, 0), mm.corrected_bits); try testing.expect(mm.reliable); try testing.expectEqual(message.Source.adsb, mm.source); try testing.expectEqual(ScoreRank.df17_unknown, mm.score.?); try testing.expectEqual(@as(u5, 4), mm.metype); try testing.expectEqualStrings("KLM1023 ", &mm.callsign.?); // Type 4 subtype 0 is category A0: no category information. try testing.expectEqual(@as(?u8, 0xa0), mm.category); } test "an airborne position decodes its altitude and CPR fields" { var decoder = try testDecoder(); defer decoder.deinit(testing.allocator); var mm: Message = .empty; try decode(&decoder, &mm, &df17_position); try testing.expectEqual(@as(u5, 11), mm.metype); try testing.expectEqual(@as(i32, 38000), mm.altitude_baro.?.value); try testing.expectEqual(message.AltitudeUnit.feet, mm.altitude_baro.?.unit); const position = mm.cpr.?; try testing.expectEqual(message.CprType.airborne, position.type); try testing.expectEqual(cpr.Frame.even, position.frame); try testing.expectEqual(@as(u17, 93000), position.encoded.latitude); try testing.expectEqual(@as(u17, 51372), position.encoded.longitude); // The capability field of this DF17 says airborne outright, which the // position message does not weaken. try testing.expectEqual(message.AirGround.airborne, mm.airground); } test "a frame of all zeros is thrown away" { var decoder = try testDecoder(); defer decoder.deinit(testing.allocator); var mm: Message = .empty; const zeros: [14]u8 = @splat(0); try testing.expectEqual(ScoreRank.all_zeros, score(&decoder, &zeros)); try testing.expectError(error.Implausible, decode(&decoder, &mm, &zeros)); } test "a single-bit error is corrected and the frame still decodes" { var decoder = try testDecoder(); defer decoder.deinit(testing.allocator); for (0..modes.max_message_bits) |bit| { var damaged = df17_ident; damaged[bit / 8] ^= @as(u8, 0x80) >> @intCast(bit % 8); var mm: Message = .empty; try decode(&decoder, &mm, &damaged); try testing.expectEqual(@as(u8, 1), mm.corrected_bits); try testing.expect(!mm.reliable); try testing.expectEqualSlices(u8, &df17_ident, &mm.msg); // What gets forwarded is what arrived, not the correction. try testing.expectEqualSlices(u8, &damaged, &mm.verbatim); try testing.expectEqual(@as(u32, 0x4840d6), mm.address); } } test "a decoded aircraft vouches for its address afterwards" { var decoder = try testDecoder(); defer decoder.deinit(testing.allocator); // A DF4 whose implied address is 0x4840d6 scores as unknown until // something has been heard from that aircraft. try testing.expect(!decoder.filter.contains(0x4840d6)); var mm: Message = .empty; try decode(&decoder, &mm, &df17_ident); try testing.expect(decoder.filter.contains(0x4840d6)); } test "identity fields unpack to hex-per-octal-digit squawks" { // Squawk 7700, the general emergency code: A=7, B=7, C=0, D=0. // A4 A2 A1 = 111 and B4 B2 B1 = 111, everything else zero. const id13: u13 = 0x0800 | 0x0200 | 0x0080 | 0x0020 | 0x0008 | 0x0002; try testing.expectEqual(@as(u16, 0x7700), decodeId13Field(id13)); try testing.expectEqual(@as(u16, 0), decodeId13Field(0)); } test "the 25-foot altitude encoding" { // With Q set the field is a count of 25-foot steps less 1000 feet, but // the count is not contiguous: the M and Q bits sit in the middle of it, // so encoding one means splitting it around them. const encode = struct { fn f(n: u32) u13 { return @intCast(((n & 0x7e0) << 2) | ((n & 0x010) << 1) | 0x0010 | (n & 0x00f)); } }.f; try testing.expectEqual(@as(i32, 0), decodeAc13Field(encode(40)).?.value); try testing.expectEqual(@as(i32, 25), decodeAc13Field(encode(41)).?.value); try testing.expectEqual(@as(i32, -1000), decodeAc13Field(encode(0)).?.value); try testing.expectEqual(message.AltitudeUnit.feet, decodeAc13Field(encode(40)).?.unit); } test "metric altitudes are not decoded" { // The M bit set: nothing in service uses this and upstream never // implemented it. try testing.expectEqual(@as(?message.Altitude, null), decodeAc13Field(0x0040)); } test "a Mode A/C reply becomes a message" { var mm: Message = .empty; decodeModeAC(&mm, 0x7700); try testing.expectEqual(message.Format.mode_ac, mm.format); try testing.expectEqual(@as(?u16, 0x7700), mm.squawk); try testing.expectEqual(message.AddressType.mode_a, mm.address_type); try testing.expect(!mm.addressIsIcao()); try testing.expectEqual(@as(?bool, false), mm.spi); try testing.expectEqual(@as(usize, 2), mm.bytes().len); } test "a Mode A/C reply with the ident bit is never read as an altitude" { var mm: Message = .empty; // 0x0010 alone is a legal altitude code; with the ident bit it is not. decodeModeAC(&mm, 0x0010); try testing.expect(mm.altitude_baro != null); mm = .empty; decodeModeAC(&mm, 0x0090); try testing.expectEqual(@as(?bool, true), mm.spi); try testing.expectEqual(@as(?message.Altitude, null), mm.altitude_baro); } test "surface movement decodes on both version scales" { // Code 1 is stopped on both. try testing.expectEqual(@as(f32, 0), decodeMovementV0(1)); try testing.expectEqual(@as(f32, 0), decodeMovementV2(1)); // The versions differ at the bottom of the scale and agree above it. try testing.expect(decodeMovementV0(5) != decodeMovementV2(5)); try testing.expectEqual(decodeMovementV0(50), decodeMovementV2(50)); try testing.expectEqual(@as(f32, 180), decodeMovementV0(124)); try testing.expectEqual(@as(f32, 0), decodeMovementV0(125)); }