// SPDX-FileCopyrightText: © 2012 Salvatore Sanfilippo // SPDX-FileCopyrightText: © 2014-2021 Oliver Jowett // SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: GPL-2.0-or-later //! The wire formats a decoded frame is passed on in. //! //! Both of these carry the frame itself rather than the decode, because what //! is downstream of a receiver is usually another decoder — an aggregator, a //! multilateration server, another copy of this program — which would rather //! have the bits and make its own judgements. What the receiver adds is the //! two things only it knows: when the frame arrived, on its own clock, and //! how strong it was. //! //! Each format also decides *which* frames to pass on, and those rules are //! here with them, since they are as much part of the format's contract as //! the byte layout. The distinction that matters is `verbatim` against //! `cooked`: verbatim output forwards the frame exactly as received, error //! correction and all left undone, so that the receiver downstream can make //! its own decision; cooked output forwards the corrected frame and drops //! the ones this receiver does not believe. const std = @import("std"); const Io = std.Io; const datetime = @import("datetime"); const fmt = @import("fmt.zig"); const json = @import("json.zig"); const message = @import("message.zig"); const modes = @import("modes.zig"); const track = @import("track.zig"); const Message = message.Message; /// Whether a frame is worth passing on in a cooked stream. /// /// `track_is_reliable` is what the tracker thinks of the aircraft, or null if /// the frame was never tracked. An unreliable frame about an aircraft nobody /// believes in is very likely noise that decoded. pub fn isCooked(mm: *const Message, track_is_reliable: ?bool) bool { // Two-bit correction is a guess too far to hand to somebody else as // though it were a received frame. if (mm.corrected_bits >= 2) return false; if (track_is_reliable) |reliable| { if (!reliable and !mm.reliable) return false; } return true; } /// The AVR text format: a line of hex per frame. /// /// The oldest of the formats and the easiest to read by eye, which is what it /// is for. A frame is written as `*8D4840D6...;`, or with a leading /// `@`-prefixed timestamp when the receiver's clock is being passed on too. pub const raw = struct { /// Write one frame. /// /// `with_timestamp` prefixes the receiver's 12 MHz clock, which is what a /// multilateration client needs and what nothing else wants. pub fn write(w: *Io.Writer, mm: *const Message, with_timestamp: bool) Io.Writer.Error!void { if (with_timestamp and mm.timestamp_12mhz != 0) { try w.print("@{X:0>12}", .{mm.timestamp_12mhz}); } else { try w.writeByte('*'); } for (mm.bytes()) |byte| try w.print("{X:0>2}", .{byte}); try w.writeAll(";\n"); } /// Sent when nothing else has been for a while, so that a reader can tell /// a quiet receiver from a dead one. pub const heartbeat = "*0000;\n"; /// Whether to forward a frame at all. Multilateration results are never /// forwarded in this format: they are not received frames and the format /// has no way of saying so. pub fn shouldSend(mm: *const Message, track_is_reliable: ?bool) bool { if (mm.source == .mlat) return false; return isCooked(mm, track_is_reliable); } }; /// The Beast binary format, as the Mode-S Beast and the Radarcape produce it. /// /// A frame becomes an escape byte, a type, a six-byte timestamp, a signal /// level and the frame itself. Any `0x1a` in the payload is doubled, which is /// what makes the escape byte findable again after a resynchronisation. pub const beast = struct { /// The byte that begins every frame, and which is doubled when it occurs /// inside one. pub const escape = 0x1a; /// What kind of frame follows the escape. pub const Kind = enum(u8) { mode_ac = '1', mode_s_short = '2', mode_s_long = '3', /// The kind a frame of this many bytes is, or null if no Beast frame /// is that size. pub fn fromLength(len: usize) ?Kind { return switch (len) { 2 => .mode_ac, 7 => .mode_s_short, 14 => .mode_s_long, else => null, }; } }; /// Write one frame. /// /// `frame` is the bytes to send, which is the corrected frame for cooked /// output and the received one for verbatim. pub fn write(w: *Io.Writer, timestamp: u64, signal_level: f64, frame: []const u8) Io.Writer.Error!void { const kind = Kind.fromLength(frame.len) orelse return; try w.writeByte(escape); try w.writeByte(@intFromEnum(kind)); // The timestamp is six bytes, big-endian: the low 48 bits of the // receiver's 12 MHz clock, which wraps about every six and a half // hours. var shift: u6 = 40; while (true) : (shift -= 8) { try writeEscaped(w, @truncate(timestamp >> shift)); if (shift == 0) break; } try writeEscaped(w, encodeSignalLevel(signal_level)); for (frame) |byte| try writeEscaped(w, byte); } /// The signal level as one byte: the amplitude rather than the power, so /// that the scale is linear in what a receiver's AGC sees. /// /// Zero is reserved for "no signal information", so a frame that really /// was received, however faintly, is reported as at least one. pub fn encodeSignalLevel(signal_level: f64) u8 { const scaled = @round(@sqrt(signal_level) * 255); if (scaled > 255) return 255; if (scaled < 1) return if (signal_level > 0) 1 else 0; return @intFromFloat(scaled); } fn writeEscaped(w: *Io.Writer, byte: u8) Io.Writer.Error!void { try w.writeByte(byte); if (byte == escape) try w.writeByte(escape); } /// A Mode A/C frame of all zeros, sent to keep a quiet connection alive. /// The frame that tells an aggregator whose feed this is. /// /// `0x1a 0xe4` and then exactly thirty-six characters of identifier, /// padded with `f` if the one given is shorter. Sent once, before any /// messages, so the far end knows from the first frame. pub fn writeUuid(w: *Io.Writer, uuid: []const u8) Io.Writer.Error!void { var padded: [36]u8 = @splat('f'); const n = @min(uuid.len, padded.len); @memcpy(padded[0..n], uuid[0..n]); try w.writeByte(escape); try w.writeByte(0xe4); try w.writeAll(&padded); } /// The shortest identifier that will be accepted. Anything shorter is /// almost certainly a mistake rather than a deliberately short name, and /// padding it out to thirty-six characters would silently feed under an /// identifier nobody chose. pub const min_uuid_len = 28; pub const heartbeat = [_]u8{ escape, '1', 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /// Whether to forward a frame in a cooked Beast stream. pub fn shouldSendCooked(mm: *const Message, track_is_reliable: ?bool, forward_mlat: bool) bool { if (mm.source == .mlat and !forward_mlat) return false; return isCooked(mm, track_is_reliable); } /// Whether to forward a frame in a verbatim Beast stream, which passes on /// everything it can. pub fn shouldSendVerbatim(mm: *const Message, forward_mlat: bool) bool { return !(mm.source == .mlat and !forward_mlat); } }; const testing = std.testing; fn testMessage(frame: []const u8) Message { var mm: Message = .empty; @memcpy(mm.msg[0..frame.len], frame); @memcpy(mm.verbatim[0..frame.len], frame); mm.len = @intCast(frame.len); mm.format = .{ .mode_s = @truncate(frame[0] >> 3) }; return mm; } const df17 = [_]u8{ 0x8d, 0x48, 0x40, 0xd6, 0x20, 0x2c, 0xc3, 0x71, 0xc3, 0x2c, 0xe0, 0x57, 0x60, 0x98 }; test "raw output is a line of hex" { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); var mm = testMessage(&df17); try raw.write(&w, &mm, false); try testing.expectEqualStrings("*8D4840D6202CC371C32CE0576098;\n", w.buffered()); } test "raw output can carry the receiver clock" { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); var mm = testMessage(&df17); mm.timestamp_12mhz = 0x0123456789ab; try raw.write(&w, &mm, true); try testing.expectEqualStrings("@0123456789AB8D4840D6202CC371C32CE0576098;\n", w.buffered()); // A frame with no timestamp falls back to the plain form rather than // claiming a time of zero. var without = testMessage(&df17); var second: Io.Writer = .fixed(&buf); try raw.write(&second, &without, true); try testing.expectEqual(@as(u8, '*'), second.buffered()[0]); } test "Beast output is escape, type, timestamp, level, frame" { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try beast.write(&w, 0x0123456789ab, 0.25, &df17); const written = w.buffered(); try testing.expectEqual(@as(u8, 0x1a), written[0]); try testing.expectEqual(@as(u8, '3'), written[1]); try testing.expectEqualSlices(u8, &.{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab }, written[2..8]); // sqrt(0.25) * 255 = 127.5, rounded away from zero. try testing.expectEqual(@as(u8, 128), written[8]); try testing.expectEqualSlices(u8, &df17, written[9..]); } test "Beast doubles the escape byte inside a frame" { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); // A short frame whose first byte is the escape byte, and a timestamp // containing one too. const frame = [_]u8{ 0x1a, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x1a }; try beast.write(&w, 0x1a0000000000, 0, &frame); const written = w.buffered(); try testing.expectEqual(@as(u8, 0x1a), written[0]); try testing.expectEqual(@as(u8, '2'), written[1]); // The first timestamp byte is 0x1a, so it is doubled. try testing.expectEqualSlices(u8, &.{ 0x1a, 0x1a }, written[2..4]); // Three escape bytes in the payload, so three extra bytes overall: two // header, six timestamp plus one doubled, one level, seven payload plus // three doubled. try testing.expectEqual(@as(usize, 2 + 7 + 1 + 10), written.len); } test "signal levels map onto a byte without losing a weak signal" { try testing.expectEqual(@as(u8, 0), beast.encodeSignalLevel(0)); try testing.expectEqual(@as(u8, 255), beast.encodeSignalLevel(1.0)); try testing.expectEqual(@as(u8, 255), beast.encodeSignalLevel(2.0)); // clamped // A real but very faint signal still reports as received. try testing.expectEqual(@as(u8, 1), beast.encodeSignalLevel(1e-9)); } test "Beast frame kinds follow the frame length" { try testing.expectEqual(beast.Kind.mode_ac, beast.Kind.fromLength(2).?); try testing.expectEqual(beast.Kind.mode_s_short, beast.Kind.fromLength(7).?); try testing.expectEqual(beast.Kind.mode_s_long, beast.Kind.fromLength(14).?); try testing.expectEqual(@as(?beast.Kind, null), beast.Kind.fromLength(9)); } test "cooked output drops guesses and unbelieved frames" { var mm = testMessage(&df17); mm.reliable = true; try testing.expect(isCooked(&mm, null)); try testing.expect(isCooked(&mm, true)); try testing.expect(isCooked(&mm, false)); // the frame vouches for itself mm.reliable = false; try testing.expect(isCooked(&mm, null)); // never tracked, so no opinion try testing.expect(isCooked(&mm, true)); try testing.expect(!isCooked(&mm, false)); mm.reliable = true; mm.corrected_bits = 2; try testing.expect(!isCooked(&mm, true)); } test "multilateration results are never sent as raw frames" { var mm = testMessage(&df17); mm.reliable = true; mm.source = .mlat; try testing.expect(!raw.shouldSend(&mm, null)); // Beast will forward them, but only when asked to. try testing.expect(!beast.shouldSendCooked(&mm, null, false)); try testing.expect(beast.shouldSendCooked(&mm, null, true)); } /// The BaseStation format, as the SBS-1 receiver produced it. /// /// A line of comma-separated fields per message, with a local wall-clock /// timestamp — twice, once for when the message arrived and once for when the /// line was written. It is the oldest interchange format still in wide use /// and the one most third-party software speaks, which is why the layout is /// reproduced field for field, empty fields and all: a consumer counts /// commas. pub const sbs = struct { /// What the format needs to know beyond the message itself. pub const Options = struct { /// Report geometric altitudes and rates in preference to barometric /// ones, suffixing them with `H`. Off by default, because the format /// predates the distinction and most consumers do not expect it. use_gnss: bool = false, }; /// Which BaseStation message type a frame becomes, or null if the format /// has nothing to say about it. pub fn messageType(mm: *const Message) ?u8 { return switch (mm.format) { .mode_ac => null, .mode_s => |df| switch (df) { 4, 20 => 5, // surveillance altitude reply 5, 21 => 6, // surveillance identity reply 0, 16 => 7, // air-to-air surveillance 11 => 8, // all-call reply 17, 18 => switch (mm.metype) { 1...4 => 1, // identification 5...8 => 2, // surface position 9...18 => 3, // airborne position 19 => 4, // airborne velocity else => null, }, else => null, }, }; } /// Whether to send a frame at all. /// /// Stricter than the other formats: BaseStation carries decoded values /// rather than the frame, so a wrong decode becomes a wrong aircraft /// rather than something the reader can check for itself. pub fn shouldSend(mm: *const Message, aircraft: ?*const track.Aircraft) bool { // The format is about aircraft, so an untracked message has nothing // to be about. const a = aircraft orelse return false; if (mm.corrected_bits >= 2) return false; if (mm.source == .mlat) return false; if (!mm.reliable and !a.reliable) return false; // Anonymous and track-file identifiers would be indistinguishable // from real addresses in this format. if (!mm.addressIsIcao()) return false; return messageType(mm) != null; } /// Write one message. /// /// `now_ms` is the current wall-clock time in milliseconds, which the /// format carries alongside the message's own arrival time. pub fn write( w: *Io.Writer, mm: *const Message, aircraft: *const track.Aircraft, zone: ?datetime.TimeZone, now_ms: u64, options: Options, ) Io.Writer.Error!void { const kind = messageType(mm) orelse return; try w.print("MSG,{d},1,1,{X:0>6},1,", .{ kind, mm.address }); try writeTimestamp(w, zone, mm.system_timestamp_ms); try w.writeByte(','); try writeTimestamp(w, zone, now_ms); // Field 11: the callsign. if (mm.callsign) |*callsign| { try w.print(",{s}", .{callsign}); } else { try w.writeByte(','); } try writeAltitude(w, mm, aircraft, options); // Field 13: ground speed. try w.writeByte(','); if (mm.gs) |speed| try fmt.fixed(w, 0, speed.selected); // Field 14: ground track. Only a real track, not a heading. try w.writeByte(','); if (mm.heading) |heading| { if (heading.type == .ground_track) try fmt.fixed(w, 0, heading.degrees); } // Fields 15 and 16: the position. if (mm.decoded_position) |solved| { try w.writeByte(','); try fmt.fixed(w, 5, solved.position.latitude); try w.writeByte(','); try fmt.fixed(w, 5, solved.position.longitude); } else { try w.writeAll(",,"); } try writeVerticalRate(w, mm, options); // Field 18: the squawk. try w.writeByte(','); if (mm.squawk) |squawk| try w.print("{x:0>4}", .{squawk}); // Field 19: the squawk-changed alert. try writeFlag(w, mm.alert); // Field 20: whether the squawk is an emergency code. try w.writeByte(','); if (mm.squawk) |squawk| { try w.writeAll(switch (squawk) { 0x7500, 0x7600, 0x7700 => "-1", else => "0", }); } // Field 21: the ident button. try writeFlag(w, mm.spi); // Field 22: on the ground. try w.writeByte(','); switch (mm.airground) { .ground => try w.writeAll("-1"), .airborne => try w.writeAll("0"), .invalid, .uncertain => {}, } try w.writeAll("\r\n"); } /// Fields 12 and 17 both choose between the barometric and geometric /// readings, and both will derive the one they want from the other and /// the difference between them if the aircraft has reported it. fn writeAltitude( w: *Io.Writer, mm: *const Message, aircraft: *const track.Aircraft, options: Options, ) Io.Writer.Error!void { const delta_valid = aircraft.geom_delta.isValid(mm.system_timestamp_ms); try w.writeByte(','); if (options.use_gnss) { if (mm.altitude_geom) |altitude| { try w.print("{d}H", .{altitude.value}); } else if (mm.altitude_baro) |altitude| { if (delta_valid) { try w.print("{d}H", .{altitude.value + aircraft.geom_delta.value}); } else { try w.print("{d}", .{altitude.value}); } } } else { if (mm.altitude_baro) |altitude| { try w.print("{d}", .{altitude.value}); } else if (mm.altitude_geom) |altitude| { if (delta_valid) try w.print("{d}", .{altitude.value - aircraft.geom_delta.value}); } } } fn writeVerticalRate(w: *Io.Writer, mm: *const Message, options: Options) Io.Writer.Error!void { try w.writeByte(','); if (options.use_gnss) { if (mm.geom_rate) |rate| { try w.print("{d}H", .{rate}); } else if (mm.baro_rate) |rate| { try w.print("{d}", .{rate}); } } else { if (mm.baro_rate) |rate| { try w.print("{d}", .{rate}); } else if (mm.geom_rate) |rate| { try w.print("{d}", .{rate}); } } } /// A three-state flag: -1 for set, 0 for clear, empty for not reported. fn writeFlag(w: *Io.Writer, flag: ?bool) Io.Writer.Error!void { try w.writeByte(','); if (flag) |set| try w.writeAll(if (set) "-1" else "0"); } /// The date and time in the local zone, to the millisecond, as two /// comma-separated fields. fn writeTimestamp(w: *Io.Writer, zone: ?datetime.TimeZone, millis: u64) Io.Writer.Error!void { // With no zone the times are UTC, which is what a receiver with no // timezone data — a container image, say — can honestly say. const local = if (zone) |z| z.atTimestamp(@intCast(millis / 1000)) else datetime.Instant.fromMilliTimestamp(@intCast(millis)).asDateTime(); // The year is signed, and a zero-padded signed integer carries its // sign; every year this format will ever see is positive. try w.print("{d:0>4}/{d:0>2}/{d:0>2},{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}", .{ @as(u32, @intCast(@max(local.year, 0))), @intFromEnum(local.month), local.day, local.hour, local.minute, local.second, millis % 1000, }); } /// Sent when nothing else has been for a while. Upstream's comment on it /// reads "is there a better one?", and there is not: the format has no /// keepalive, so an empty line is what everything has learned to ignore. pub const heartbeat = "\r\n"; }; /// The Stratux output: one JSON object per message, for the portable /// receivers that run the Stratux software. /// /// It is the only format here that carries the decode rather than the frame, /// alongside a couple of things about the receiver itself — the signal level /// and the gain the tuner is at — because the consumer is a display rather /// than another decoder. The field names are Stratux's own, from its /// `traffic.go`, which is why they look nothing like the rest of this file. pub const stratux = struct { /// The most one message can produce. Upstream reserves this much and /// complains if a message overruns it. pub const max_packet_size = 1000; /// Whether to send a frame at all. pub fn shouldSend(mm: *const Message, aircraft: ?*const track.Aircraft) bool { // The format is about aircraft, so an untracked message has nothing // to be about. const a = aircraft orelse return false; // A two-bit correction is too much of a guess to hand to a display // that will draw an aeroplane from it. if (mm.corrected_bits >= 2) return false; return mm.reliable or a.reliable; } /// Write one message as a Stratux traffic object. pub fn write( w: *Io.Writer, mm: *const Message, aircraft: *const track.Aircraft, gain_db: f64, ) Io.Writer.Error!void { // The CA field is overloaded: the capability for DF11 and DF17, the // control field for DF18, and nothing at all otherwise. const cacf: u32 = switch (mm.format) { .mode_ac => 0, .mode_s => |df| switch (df) { 11, 17 => mm.raw.ca, 18 => mm.raw.cf, else => 0, }, }; try w.print("{{\"Icao_addr\":{d},\"DF\":{d},\"CA\":{d},\"TypeCode\":{d},\"SubtypeCode\":{d},\"SignalLevel\":", .{ mm.address, switch (mm.format) { .mode_ac => @as(u32, 32), .mode_s => |df| @as(u32, df), }, cacf, mm.metype, mm.mesub, }); try fmt.fixed(w, 6, mm.signal_level); try w.writeAll(",\"Gain\":"); try fmt.fixed(w, 6, gain_db); try w.print(",\"IsMlat\":{s},", .{if (mm.source == .mlat) "true" else "false"}); if (mm.callsign) |callsign| { try w.writeAll("\"Tail\":\""); try json.writeEscaped(w, &callsign); try w.writeAll("\","); } else { try w.writeAll("\"Tail\":null,"); } // Barometric altitude for preference; geometric only if that is all // there is, and then said to be geometric. var altitude_is_geometric = false; if (mm.altitude_baro) |altitude| { try w.print("\"Alt\":{d},", .{altitude.value}); } else if (mm.altitude_geom) |altitude| { try w.print("\"Alt\":{d},", .{altitude.value}); altitude_is_geometric = true; } else { try w.writeAll("\"Alt\":null,"); } try w.print("\"AltIsGNSS\":{s},", .{if (altitude_is_geometric) "true" else "false"}); if (aircraft.geom_delta.get(mm.system_timestamp_ms)) |delta| { try w.print("\"GnssDiffFromBaroAlt\":{d},", .{delta}); } else { try w.writeAll("\"GnssDiffFromBaroAlt\":null,"); } if (mm.gs) |speed| { try w.writeAll("\"Speed_valid\":true,\"Speed\":"); try fmt.fixed(w, 0, speed.selected); try w.writeAll(","); } else { try w.writeAll("\"Speed_valid\":false,\"Speed\":null,"); } // Only a ground track counts as a track; a heading is a different // thing and the field has no room to say which it got. if (mm.heading) |heading| { if (heading.type == .ground_track) { try w.writeAll("\"Track\":"); try fmt.fixed(w, 0, heading.degrees); try w.writeAll(","); } else { try w.writeAll("\"Track\":null,"); } } else { try w.writeAll("\"Track\":null,"); } if (mm.decoded_position) |decoded| { try w.writeAll("\"Lat\":"); try fmt.fixed(w, 6, decoded.position.latitude); try w.writeAll(",\"Lng\":"); try fmt.fixed(w, 6, decoded.position.longitude); try w.writeAll(",\"Position_valid\":true,"); } else { try w.writeAll("\"Lat\":null,\"Lng\":null,\"Position_valid\":false,"); } if (mm.baro_rate) |rate| { try w.print("\"Vvel\":{d},", .{rate}); } else if (mm.geom_rate) |rate| { try w.print("\"Vvel\":{d},", .{rate}); } else { try w.writeAll("\"Vvel\":null,"); } // The squawk is four octal digits packed one per nibble, and this // prints those nibbles as hex — so 7700 comes out as 7700. It is a // strange way to write it and it is the way Stratux reads it. if (mm.squawk) |squawk| { try w.print("\"Squawk\":{x},", .{squawk}); } else { try w.writeAll("\"Squawk\":null,"); } try w.writeAll(switch (mm.airground) { .ground => "\"OnGround\":true,", .airborne => "\"OnGround\":false,", .invalid, .uncertain => "\"OnGround\":null,", }); if (mm.accuracy.nac_p) |nac_p| { try w.print("\"NACp\":{d},", .{nac_p}); } else { try w.writeAll("\"NACp\":null,"); } if (emitterCategory(mm)) |emitter| { try w.print("\"Emitter_category\":{d},", .{emitter}); } else { try w.writeAll("\"Emitter_category\":null,"); } try w.writeAll("\"Timestamp\":\""); try writeTimestamp(w, mm.system_timestamp_ms); try w.writeAll("\"}\r\n"); } /// The ADS-B emitter category, flattened into one number the way /// Stratux wants it: the subtype, with a few bits saying which /// identification message it came from. fn emitterCategory(mm: *const Message) ?u8 { switch (mm.format) { .mode_ac => return null, .mode_s => |df| if (df != 17 and df != 18) return null, } return switch (mm.metype) { 1 => @as(u8, mm.mesub) | 0x18, 2 => @as(u8, mm.mesub) | 0x10, 3 => @as(u8, mm.mesub) | 0x08, 4 => @as(u8, mm.mesub), else => null, }; } /// `2016-02-20T06:35:43.155Z`, always in UTC. fn writeTimestamp(w: *Io.Writer, millis: u64) Io.Writer.Error!void { const utc = datetime.Instant.fromMilliTimestamp(@intCast(millis)).asDateTime(); try w.print("{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}Z", .{ @as(u32, @intCast(utc.year)), @intFromEnum(utc.month), utc.day, utc.hour, utc.minute, utc.second, millis % 1000, }); } /// Sent when nothing else has been for a while. The address is /// 0x07ffffff, which overflows a 24-bit ICAO address and so cannot be /// mistaken for an aircraft. pub const heartbeat = "{\"Icao_addr\":134217727}\r\n"; }; test "a Stratux object names the fields Stratux reads" { var mm: Message = .empty; mm.format = .{ .mode_s = 17 }; mm.raw.ca = 5; mm.metype = 19; mm.mesub = 1; mm.address = 0x4840d6; mm.reliable = true; mm.system_timestamp_ms = 1_788_805_845_123; mm.signal_level = 0.25; mm.altitude_baro = .{ .value = 38000, .unit = .feet }; mm.gs = .exact(420.5); mm.heading = .{ .degrees = 90.5, .type = .ground_track }; mm.baro_rate = -1024; mm.squawk = 0x7700; mm.airground = .airborne; mm.accuracy.nac_p = 9; var aircraft: track.Aircraft = .{ .address = mm.address, .address_type = .adsb_icao, .reliable = true }; var buf: [output_stratux_test_buffer]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expect(stratux.shouldSend(&mm, &aircraft)); try stratux.write(&w, &mm, &aircraft, 49.6); try testing.expectEqualStrings( "{\"Icao_addr\":4735190,\"DF\":17,\"CA\":5,\"TypeCode\":19,\"SubtypeCode\":1" ++ ",\"SignalLevel\":0.250000,\"Gain\":49.600000,\"IsMlat\":false,\"Tail\":null" ++ ",\"Alt\":38000,\"AltIsGNSS\":false,\"GnssDiffFromBaroAlt\":null" ++ ",\"Speed_valid\":true,\"Speed\":420,\"Track\":90" ++ ",\"Lat\":null,\"Lng\":null,\"Position_valid\":false" ++ ",\"Vvel\":-1024,\"Squawk\":7700,\"OnGround\":false,\"NACp\":9" ++ ",\"Emitter_category\":null" ++ ",\"Timestamp\":\"2026-09-07T18:30:45.123Z\"}\r\n", w.buffered(), ); } const output_stratux_test_buffer = stratux.max_packet_size; test "the feed identifier frame is padded to thirty-six characters" { var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try beast.writeUuid(&w, "0033062d-e17e-4389-91a9-79ebb967fb4c"); const written = w.buffered(); try testing.expectEqual(@as(usize, 38), written.len); try testing.expectEqual(@as(u8, beast.escape), written[0]); try testing.expectEqual(@as(u8, 0xe4), written[1]); try testing.expectEqualStrings("0033062d-e17e-4389-91a9-79ebb967fb4c", written[2..]); // A shorter one is padded out rather than sent short, so the frame is // always the same length. w = .fixed(&buf); try beast.writeUuid(&w, "0033062d-e17e-4389-91a9-79eb"); try testing.expectEqual(@as(usize, 38), w.buffered().len); try testing.expectEqualStrings("0033062d-e17e-4389-91a9-79ebffffffff", w.buffered()[2..]); } test "a BaseStation line has twenty-two fields" { var mm: Message = .empty; mm.format = .{ .mode_s = 17 }; mm.metype = 11; mm.address = 0x4840d6; mm.reliable = true; mm.system_timestamp_ms = 1_788_805_845_123; mm.altitude_baro = .{ .value = 38000, .unit = .feet }; mm.squawk = 0x7700; mm.airground = .airborne; mm.alert = false; mm.spi = false; var aircraft: track.Aircraft = .{ .address = mm.address, .address_type = .adsb_icao, .reliable = true }; var buf: [256]u8 = undefined; var w: Io.Writer = .fixed(&buf); try sbs.write(&w, &mm, &aircraft, null, 1_788_805_846_456, .{}); const line = w.buffered(); try testing.expect(std.mem.endsWith(u8, line, "\r\n")); var fields: std.ArrayList([]const u8) = .empty; defer fields.deinit(testing.allocator); var it = std.mem.splitScalar(u8, line[0 .. line.len - 2], ','); while (it.next()) |field| try fields.append(testing.allocator, field); try testing.expectEqual(@as(usize, 22), fields.items.len); try testing.expectEqualStrings("MSG", fields.items[0]); try testing.expectEqualStrings("3", fields.items[1]); // airborne position try testing.expectEqualStrings("4840D6", fields.items[4]); try testing.expectEqualStrings("2026/09/07", fields.items[6]); try testing.expectEqualStrings("18:30:45.123", fields.items[7]); try testing.expectEqualStrings("18:30:46.456", fields.items[9]); try testing.expectEqualStrings("", fields.items[10]); // no callsign try testing.expectEqualStrings("38000", fields.items[11]); try testing.expectEqualStrings("", fields.items[12]); // no ground speed try testing.expectEqualStrings("", fields.items[14]); // no position try testing.expectEqualStrings("7700", fields.items[17]); try testing.expectEqualStrings("0", fields.items[18]); // alert clear try testing.expectEqualStrings("-1", fields.items[19]); // 7700 is an emergency try testing.expectEqualStrings("0", fields.items[20]); // ident clear try testing.expectEqualStrings("0", fields.items[21]); // airborne } test "BaseStation message types follow the downlink format" { var mm: Message = .empty; mm.format = .{ .mode_s = 4 }; try testing.expectEqual(@as(?u8, 5), sbs.messageType(&mm)); mm.format = .{ .mode_s = 21 }; try testing.expectEqual(@as(?u8, 6), sbs.messageType(&mm)); mm.format = .{ .mode_s = 16 }; try testing.expectEqual(@as(?u8, 7), sbs.messageType(&mm)); mm.format = .{ .mode_s = 11 }; try testing.expectEqual(@as(?u8, 8), sbs.messageType(&mm)); mm.format = .{ .mode_s = 17 }; mm.metype = 4; try testing.expectEqual(@as(?u8, 1), sbs.messageType(&mm)); // identification mm.metype = 7; try testing.expectEqual(@as(?u8, 2), sbs.messageType(&mm)); // surface position mm.metype = 11; try testing.expectEqual(@as(?u8, 3), sbs.messageType(&mm)); // airborne position mm.metype = 19; try testing.expectEqual(@as(?u8, 4), sbs.messageType(&mm)); // velocity mm.metype = 31; try testing.expectEqual(@as(?u8, null), sbs.messageType(&mm)); // operational status // The format has nothing to say about Mode A/C or Comm-D. mm.format = .mode_ac; try testing.expectEqual(@as(?u8, null), sbs.messageType(&mm)); mm.format = .{ .mode_s = 24 }; try testing.expectEqual(@as(?u8, null), sbs.messageType(&mm)); } test "BaseStation refuses what it cannot express" { var aircraft: track.Aircraft = .{ .address = 0x4840d6, .address_type = .adsb_icao, .reliable = true }; var mm: Message = .empty; mm.format = .{ .mode_s = 17 }; mm.metype = 11; mm.reliable = true; try testing.expect(sbs.shouldSend(&mm, &aircraft)); // An untracked message has no aircraft to be about. try testing.expect(!sbs.shouldSend(&mm, null)); // A two-bit correction is too much of a guess for a format that carries // decoded values rather than the frame. mm.corrected_bits = 2; try testing.expect(!sbs.shouldSend(&mm, &aircraft)); mm.corrected_bits = 0; // An anonymous identifier would be indistinguishable from an address. mm.address |= message.non_icao_address; try testing.expect(!sbs.shouldSend(&mm, &aircraft)); } test "geometric altitudes are reported only when asked for" { var mm: Message = .empty; mm.format = .{ .mode_s = 17 }; mm.metype = 11; mm.address = 0x4840d6; mm.reliable = true; mm.altitude_baro = .{ .value = 38000, .unit = .feet }; mm.geom_delta = 300; var aircraft: track.Aircraft = .{ .address = mm.address, .address_type = .adsb_icao, .reliable = true }; _ = aircraft.geom_delta.set(0, .adsb, 300); var buf: [256]u8 = undefined; var plain: Io.Writer = .fixed(&buf); try sbs.write(&plain, &mm, &aircraft, null, 0, .{}); try testing.expect(std.mem.indexOf(u8, plain.buffered(), ",38000,") != null); // With --use-gnss the barometric altitude plus the reported difference // becomes a geometric one, marked with an H. var gnss: Io.Writer = .fixed(&buf); try sbs.write(&gnss, &mm, &aircraft, null, 0, .{ .use_gnss = true }); try testing.expect(std.mem.indexOf(u8, gnss.buffered(), ",38300H,") != null); }