Something went wrong. Try again.
A port of FlightAware's dump1090, a Mode S and ADS-B decoder for software defined radios, to Zig 0.16.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743// SPDX-FileCopyrightText: © 2014-2021 Oliver Jowett <oliver@mutability.co.uk>// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: GPL-2.0-or-later
//! FlightAware's tab-separated format.//!//! Where every other output here carries the frame and lets whatever is//! downstream decode it again, this carries the *track*: a line per aircraft//! saying what has changed about it since the last line, which is what an//! aggregator wants and what PiAware forwards.//!//! Three things follow from it being a change feed rather than a message//! feed, and between them they are most of this file://!//! * Every aircraft carries a shadow copy of what was last said about it//! (`track.Fatsv`), and a field is sent only when it has moved far enough//! to be worth the bytes — fifty feet of altitude, two degrees of track,//! twenty-five knots of speed. Fields that rarely change are sent only when//! they change at all, and re-sent in full every ten minutes so that a//! consumer joining late is not left guessing.//!//! * How often an aircraft is reported depends on what it is doing. A change//! worth acting on goes out immediately; an aircraft on the ground every//! second; below ten thousand feet every five; above it every ten, and//! thirty when nothing is changing. A Mode S track with no position at all//! gets thirty seconds whatever it does.//!//! * Each field carries its own provenance — how many seconds old it is and//! which kind of source it came from — because a consumer merging several//! receivers has to know which of two disagreeing values to believe.//! Anything from multilateration or a Mode A/C reply is not forwarded at//! all: it is this receiver's inference, not the aircraft's word.//!//! Upstream generates this in `faup1090`, a second program that reads the//! Beast output of the first. This port has no `faup1090`, so the format//! lives here and is served on `.outputs.fatsv` like any other output — and//! handed straight to `src/adept.zig`, since a line of this *is* an adept//! message and FlightAware's uplink needs no conversion to accept one.
const std = @import("std");const Io = std.Io;
const fmt = @import("fmt.zig");const json = @import("json.zig");const message = @import("message.zig");const track = @import("track.zig");const Message = message.Message;
/// The format version this speaks, sent as the first field of every line.pub const version = "9E";
/// The most one line may occupy. Upstream's limit, and lines are dropped/// rather than truncated if they somehow exceed it.pub const max_line = 800;
/// How the emission rate is scaled. Upstream's `--faup-rate-multiplier`:/// larger means more often.pub const default_rate_multiplier: f64 = 1.0;
/// How long between full re-sends of the fields that are otherwise only sent/// when they change.pub const force_emit_interval_ms = 600_000;
/// What the emitter needs to know beyond the aircraft itself.pub const Options = struct { /// Scales how often each aircraft is reported. rate_multiplier: f64 = default_rate_multiplier, /// Whether to forward Comm-B replies that could not be identified, for /// analysis at the other end. upload_unknown_commb: bool = false,};
/// The one-letter provenance a field carries.////// Null for the sources this format does not forward: a multilaterated/// position and a Mode A/C reply are both this receiver's own inference, and/// saying otherwise would let them outvote something an aircraft actually/// transmitted.fn sourceLetter(source: message.Source) ?[]const u8 { return switch (source) { .mode_s => "U", .mode_s_checked => "S", .tisb => "T", .adsr => "R", .adsb => "A", .invalid, .mode_ac, .mlat => null, };}
/// Write one plain `key<TAB>value<TAB>` pair.fn field(w: *Io.Writer, key: []const u8, comptime format: []const u8, args: anytype) Io.Writer.Error!void { try w.print("{s}\t" ++ format ++ "\t", .{key} ++ args);}
/// Whether a tracked field is worth sending, and if so what to stamp it with.////// Four ways to be not worth sending, all of them upstream's: a source this/// format does not forward, a value that has expired, one stamped in the/// future, and one not touched since the last line went out. A fifth, an age/// over four minutes, is a limit of the wire format — the age is one byte.fn meta( validity: track.Validity, now: u64, last_emitted: u64,) ?struct { age: u64, source: []const u8 } { const letter = sourceLetter(validity.source) orelse return null; if (!validity.isValid(now)) return null; if (validity.updated > now) return null; if (validity.updated < last_emitted) return null;
const age = (now - validity.updated) / 1000; if (age > 255) return null;
return .{ .age = age, .source = letter };}
/// The state one aircraft's line is being built with.const Line = struct { w: *Io.Writer, now: u64, last_emitted: u64,
/// Write a field carrying its age and provenance, or nothing at all if /// the value is not one to forward. fn tagged( self: Line, key: []const u8, validity: track.Validity, comptime format: []const u8, args: anytype, ) Io.Writer.Error!void { const m = meta(validity, self.now, self.last_emitted) orelse return; try self.w.print("{s}\t" ++ format ++ " {d} {s}\t", .{key} ++ args ++ .{ m.age, m.source }); }
/// The same, for a value that needs the ties-to-even formatter rather /// than a format string. fn taggedFixed( self: Line, key: []const u8, validity: track.Validity, comptime decimals: comptime_int, value: f64, ) Io.Writer.Error!void { const m = meta(validity, self.now, self.last_emitted) orelse return; try self.w.print("{s}\t", .{key}); try fmt.fixed(self.w, decimals, value); try self.w.print(" {d} {s}\t", .{ m.age, m.source }); }};
/// `A+` airborne, `G+` on the ground, `?` when nothing has said.fn airgroundName(state: message.AirGround) []const u8 { return switch (state) { .airborne => "A+", .ground => "G+", .invalid, .uncertain => "?", };}
fn navAltitudeSourceName(source: message.NavAltitudeSource) []const u8 { return switch (source) { .invalid => "invalid", .unknown => "unknown", .aircraft => "aircraft", .mcp => "mcp", .fms => "fms", };}
/// The engaged autopilot modes, space separated, in the order the format/// lists them.fn writeNavModes(w: *Io.Writer, engaged: message.NavModes) Io.Writer.Error!void { const names = [_]struct { field: []const u8, name: []const u8 }{ .{ .field = "autopilot", .name = "autopilot" }, .{ .field = "vnav", .name = "vnav" }, .{ .field = "alt_hold", .name = "althold" }, .{ .field = "approach", .name = "approach" }, .{ .field = "lnav", .name = "lnav" }, .{ .field = "tcas", .name = "tcas" }, }; var first = true; inline for (names) |mode| { if (@field(engaged, mode.field)) { if (!first) try w.writeByte(' '); try w.writeAll(mode.name); first = false; } }}
/// The header every line begins with: the version, the time, and who it is/// about. A fabricated address is `otherid` rather than `hexid`, so that a/// consumer does not take it for a real ICAO one.fn writeHeader(w: *Io.Writer, address: u32, now_ms: u64) Io.Writer.Error!void { try field(w, "_v", "{s}", .{version}); try field(w, "clock", "{d}", .{now_ms / 1000}); const key = if (address & message.non_icao_address != 0) "otherid" else "hexid"; try field(w, key, "{X:0>6}", .{address & 0xffffff});}
/// A record saying where this receiver is, sent when a Radarcape tells us.pub fn writePositionUpdate( w: *Io.Writer, latitude: f32, longitude: f32, altitude: f32, now_ms: u64,) Io.Writer.Error!void { try field(w, "_v", "{s}", .{version}); try field(w, "clock", "{d}", .{now_ms / 1000}); try field(w, "type", "{s}", .{"location_update"}); try w.writeAll("lat\t"); try fmt.fixed(w, 5, latitude); try w.writeAll("\tlon\t"); try fmt.fixed(w, 5, longitude); try w.writeAll("\talt\t"); try fmt.fixed(w, 0, altitude); try w.writeAll("\taltref\tegm96_meters\n");}
/// A record carrying one message's raw payload, for the kinds of message the/// format forwards whole rather than decoded.fn writeEventMessage( w: *Io.Writer, mm: *const Message, key: []const u8, payload: []const u8,) Io.Writer.Error!void { try writeHeader(w, mm.address, mm.system_timestamp_ms); // The address type is only worth saying when it is not the usual one. if (mm.address_type != .adsb_icao) { try field(w, "addrtype", "{s}", .{json.addressTypeName(mm.address_type)}); } try w.print("{s}\t", .{key}); for (payload) |byte| try w.print("{X:0>2}", .{byte}); try w.writeByte('\n');}
/// Which event record, if any, a message should produce.////// These are the messages the format forwards verbatim: the Comm-B capability/// and resolution-advisory reports, and their extended squitter equivalents./// Each is sent only when its payload differs from the last one seen from/// that aircraft, which for a capability report means roughly once.pub fn writeEvent( w: *Io.Writer, mm: *const Message, aircraft: *track.Aircraft, options: Options,) Io.Writer.Error!bool { // Nothing this receiver merely inferred, and nothing from a track that // has not earned trust. if (mm.source == .mlat) return false; if (!aircraft.reliable and !mm.reliable) return false;
const df = switch (mm.format) { .mode_ac => return false, .mode_s => |value| value, };
switch (df) { 20, 21 => { const payload = mm.raw.mb[0..7]; const slot: ?*[7]u8 = switch (mm.commb_format) { .datalink_caps => &aircraft.fatsv.bds_10, .acas_ra => &aircraft.fatsv.bds_30, .gicb_caps => &aircraft.fatsv.bds_17, .unknown => if (options.upload_unknown_commb) &aircraft.fatsv.unknown_commb else null, else => null, }; const key = switch (mm.commb_format) { .datalink_caps => "datalink_caps", .acas_ra => "commb_acas_ra", .gicb_caps => "gicb_caps", else => "unknown_commb", }; const target = slot orelse return false; if (std.mem.eql(u8, target, payload)) return false; @memcpy(target, payload); try writeEventMessage(w, mm, key, payload); return true; }, 17, 18 => { const payload = mm.raw.me[0..7]; // Type 28 subtype 2 is an ACAS resolution advisory; after the // first byte it is the BDS 3,0 format again. if (mm.metype == 28 and mm.mesub == 2) { if (std.mem.eql(u8, &aircraft.fatsv.es_acas_ra, payload)) return false; @memcpy(&aircraft.fatsv.es_acas_ra, payload); try writeEventMessage(w, mm, "es_acas_ra", payload); return true; } if (mm.metype == 31 and (mm.mesub == 0 or mm.mesub == 1)) { if (std.mem.eql(u8, &aircraft.fatsv.es_status, payload)) return false; @memcpy(&aircraft.fatsv.es_status, payload); try writeEventMessage(w, mm, "es_op_status", payload); return true; } return false; }, else => return false, }}
/// The shortest way round a circle between two bearings.fn headingDifference(a: f32, b: f32) f32 { const d = @abs(a - b); return if (d < 180) d else 360 - d;}
fn unsignedDifference(a: u32, b: u32) u32 { return if (a > b) a - b else b - a;}
/// Write one aircraft's line, or nothing if it has nothing new to say.////// `w` must be a fixed writer over a buffer of at least `max_line` bytes:/// whether the line is worth sending is not known until every field has been/// considered, so it is built and then either kept or wound back.////// Returns whether anything was written. `now_ms` is the wall clock, used/// only to decide whether this aircraft is due; everything the line says/// about ages and validity is relative to when the aircraft was last heard,/// which is what upstream calls `messageNow`.pub fn writeAircraft( w: *Io.Writer, aircraft: *track.Aircraft, now_ms: u64, options: Options,) Io.Writer.Error!bool { if (!aircraft.reliable) return false; // Nothing new since the last line. if (aircraft.seen < aircraft.fatsv.last_emitted) return false;
// Everything below is judged as of the moment this aircraft was last // heard, not the moment this scan runs. const heard = aircraft.seen; const last = aircraft.fatsv.last_emitted; const shadow = &aircraft.fatsv;
var altitude_valid = aircraft.altitude_baro.isValid(heard); // For a transponder that is not ADS-B, only the DF11 capability field is // trusted to say whether it is on the ground. const airground_valid = aircraft.airground.isValid(heard) and @intFromEnum(aircraft.airground.validity.source) >= @intFromEnum(message.Source.mode_s_checked); const gs_valid = aircraft.gs.isValid(heard); const squawk_valid = aircraft.squawk.isValid(heard); const callsign_valid = aircraft.callsign.isValid(heard) and !std.mem.eql(u8, &aircraft.callsign.value, " "); const position_valid = aircraft.position.isValid(heard);
// On the ground an ADS-B transponder sends no altitude at all, so a // corrupted Mode S altitude from something else overhead can otherwise // be taken as the best available and reported as "on the ground at // thirty-one thousand feet". if (airground_valid and aircraft.airground.value == .ground and @intFromEnum(aircraft.altitude_baro.validity.source) < @intFromEnum(message.Source.mode_s_checked)) { altitude_valid = false; }
const changed = (altitude_valid and @abs(aircraft.altitude_baro.value - shadow.altitude_baro) >= 50) or (aircraft.altitude_geom.isValid(heard) and @abs(aircraft.altitude_geom.value - shadow.altitude_geom) >= 50) or (aircraft.baro_rate.isValid(heard) and @abs(aircraft.baro_rate.value - shadow.baro_rate) > 500) or (aircraft.geom_rate.isValid(heard) and @abs(aircraft.geom_rate.value - shadow.geom_rate) > 500) or (aircraft.track.isValid(heard) and headingDifference(aircraft.track.value, shadow.track) >= 2) or (aircraft.track_rate.isValid(heard) and @abs(aircraft.track_rate.value - shadow.track_rate) >= 0.5) or (aircraft.roll.isValid(heard) and @abs(aircraft.roll.value - shadow.roll) >= 5.0) or (aircraft.mag_heading.isValid(heard) and headingDifference(aircraft.mag_heading.value, shadow.mag_heading) >= 2) or (aircraft.true_heading.isValid(heard) and headingDifference(aircraft.true_heading.value, shadow.true_heading) >= 2) or (gs_valid and @abs(aircraft.gs.value - shadow.gs) >= 25) or (aircraft.ias.isValid(heard) and unsignedDifference(aircraft.ias.value, shadow.ias) >= 25) or (aircraft.tas.isValid(heard) and unsignedDifference(aircraft.tas.value, shadow.tas) >= 25) or (aircraft.mach.isValid(heard) and @abs(aircraft.mach.value - shadow.mach) >= 0.02);
// Changes worth interrupting the schedule for: what the aircraft is // being told to do, who it says it is, and anything that would matter to // somebody watching. const immediate = (aircraft.nav_altitude_mcp.isValid(heard) and @abs(aircraft.nav_altitude_mcp.value - shadow.nav_altitude_mcp) > 50) or (aircraft.nav_altitude_fms.isValid(heard) and @abs(aircraft.nav_altitude_fms.value - shadow.nav_altitude_fms) > 50) or (aircraft.nav_altitude_src.isValid(heard) and aircraft.nav_altitude_src.value != shadow.nav_altitude_src) or (aircraft.nav_heading.isValid(heard) and headingDifference(aircraft.nav_heading.value, shadow.nav_heading) > 2) or (aircraft.nav_modes.isValid(heard) and @as(u8, @bitCast(aircraft.nav_modes.value)) != @as(u8, @bitCast(shadow.nav_modes))) or // 0.8 is the resolution the message carries it at. (aircraft.nav_qnh.isValid(heard) and @abs(aircraft.nav_qnh.value - shadow.nav_qnh) > 0.8) or (callsign_valid and !std.mem.eql(u8, &aircraft.callsign.value, &shadow.callsign)) or (airground_valid and aircraft.airground.value == .airborne and shadow.airground == .ground) or (airground_valid and aircraft.airground.value == .ground and shadow.airground == .airborne) or (squawk_valid and aircraft.squawk.value != shadow.squawk) or (aircraft.emergency.isValid(heard) and aircraft.emergency.value != shadow.emergency) or (aircraft.mrar_source.isValid(heard) and aircraft.mrar_source.validity.updated > last) or (aircraft.wind.isValid(heard) and aircraft.wind.validity.updated > last) or (aircraft.pressure.isValid(heard) and aircraft.pressure.validity.updated > last) or (aircraft.temperature.isValid(heard) and aircraft.temperature.validity.updated > last) or (aircraft.turbulence.isValid(heard) and aircraft.turbulence.validity.updated > last) or (aircraft.humidity.isValid(heard) and aircraft.humidity.validity.updated > last);
// How often this aircraft is worth reporting, by what it appears to be // doing. An aircraft manoeuvring near the ground is interesting every // second; one in the cruise is not. const min_age_ms: u64 = if (immediate) 0 else if (!position_valid) // A Mode S track with no position is mostly noise to a consumer. 30_000 else if ((airground_valid and aircraft.airground.value == .ground) or (altitude_valid and aircraft.altitude_baro.value < 500 and (!gs_valid or aircraft.gs.value < 200)) or (gs_valid and aircraft.gs.value < 100 and (!altitude_valid or aircraft.altitude_baro.value < 1000))) 1_000 else if (!altitude_valid or aircraft.altitude_baro.value < 10000) (if (changed) @as(u64, 5_000) else 10_000) else (if (changed) @as(u64, 10_000) else 30_000);
const adjusted = @as(f64, @floatFromInt(min_age_ms)) / options.rate_multiplier; if (@as(f64, @floatFromInt(now_ms - last)) < adjusted) return false;
const start_of_line = w.end; try writeHeader(w, aircraft.address, heard);
// The fields that hardly ever change are sent when they do, and in full // every ten minutes so that a consumer joining late is not left guessing. const force = (now_ms - shadow.last_force_emit) > force_emit_interval_ms;
if (force or aircraft.address_type != shadow.address_type) { try field(w, "addrtype", "{s}", .{json.addressTypeName(aircraft.address_type)}); } if (force or aircraft.adsb_version != shadow.adsb_version) { try field(w, "adsb_version", "{d}", .{aircraft.adsb_version orelse 0}); } if (force or (aircraft.category orelse 0) != shadow.category) { try field(w, "category", "{X:0>2}", .{aircraft.category orelse 0}); }
const line: Line = .{ .w = w, .now = heard, .last_emitted = last };
if (aircraft.nac_p.isValid(heard) and (force or aircraft.nac_p.value != shadow.nac_p)) { try line.tagged("nac_p", aircraft.nac_p.validity, "{d}", .{aircraft.nac_p.value}); } if (aircraft.nac_v.isValid(heard) and (force or aircraft.nac_v.value != shadow.nac_v)) { try line.tagged("nac_v", aircraft.nac_v.validity, "{d}", .{aircraft.nac_v.value}); } if (aircraft.sil.isValid(heard) and (force or aircraft.sil.value != shadow.sil)) { try line.tagged("sil", aircraft.sil.validity, "{d}", .{aircraft.sil.value}); } if (aircraft.sil.isValid(heard) and (force or aircraft.sil_type != shadow.sil_type)) { try line.tagged("sil_type", aircraft.sil.validity, "{s}", .{json.silTypeName(aircraft.sil_type)}); } if (aircraft.nic_baro.isValid(heard) and (force or aircraft.nic_baro.value != shadow.nic_baro)) { try line.tagged("nic_baro", aircraft.nic_baro.validity, "{d}", .{aircraft.nic_baro.value}); }
// Everything from here is the aircraft's current state, sent only if it // has been heard since the last line and has not gone stale. If none of // it qualifies, the line has nothing in it and is abandoned. const before_data = w.end;
if (airground_valid) { try line.tagged("airGround", aircraft.airground.validity, "{s}", .{airgroundName(aircraft.airground.value)}); } if (squawk_valid) { try line.tagged("squawk", aircraft.squawk.validity, "{x:0>4}", .{aircraft.squawk.value}); } if (callsign_valid) { try line.tagged("ident", aircraft.callsign.validity, "{{{s}}}", .{&aircraft.callsign.value}); } if (altitude_valid) { try line.tagged("alt", aircraft.altitude_baro.validity, "{d}", .{aircraft.altitude_baro.value}); } if (position_valid) { if (meta(aircraft.position.validity, heard, last)) |m| { const p = aircraft.position.value; try w.writeAll("position\t{"); try fmt.fixed(w, 5, p.position.latitude); try w.writeByte(' '); try fmt.fixed(w, 5, p.position.longitude); try w.print(" {d} {d}}} {d} {s}\t", .{ p.nic, p.rc, m.age, m.source }); } }
try line.tagged("alt_gnss", aircraft.altitude_geom.validity, "{d}", .{aircraft.altitude_geom.value}); try line.tagged("vrate", aircraft.baro_rate.validity, "{d}", .{aircraft.baro_rate.value}); try line.tagged("vrate_geom", aircraft.geom_rate.validity, "{d}", .{aircraft.geom_rate.value}); try line.taggedFixed("speed", aircraft.gs.validity, 1, aircraft.gs.value); try line.tagged("speed_ias", aircraft.ias.validity, "{d}", .{aircraft.ias.value}); try line.tagged("speed_tas", aircraft.tas.validity, "{d}", .{aircraft.tas.value}); try line.taggedFixed("mach", aircraft.mach.validity, 3, aircraft.mach.value); try line.taggedFixed("track", aircraft.track.validity, 1, aircraft.track.value); try line.taggedFixed("track_rate", aircraft.track_rate.validity, 2, aircraft.track_rate.value); try line.taggedFixed("roll", aircraft.roll.validity, 1, aircraft.roll.value); try line.taggedFixed("heading_magnetic", aircraft.mag_heading.validity, 1, aircraft.mag_heading.value); try line.taggedFixed("heading_true", aircraft.true_heading.validity, 1, aircraft.true_heading.value); try line.tagged("nav_alt_mcp", aircraft.nav_altitude_mcp.validity, "{d}", .{aircraft.nav_altitude_mcp.value}); try line.tagged("nav_alt_fms", aircraft.nav_altitude_fms.validity, "{d}", .{aircraft.nav_altitude_fms.value}); try line.tagged("nav_alt_src", aircraft.nav_altitude_src.validity, "{s}", .{navAltitudeSourceName(aircraft.nav_altitude_src.value)}); try line.taggedFixed("nav_heading", aircraft.nav_heading.validity, 1, aircraft.nav_heading.value); if (meta(aircraft.nav_modes.validity, heard, last)) |m| { try w.writeAll("nav_modes\t{"); try writeNavModes(w, aircraft.nav_modes.value); try w.print("}} {d} {s}\t", .{ m.age, m.source }); } try line.taggedFixed("nav_qnh", aircraft.nav_qnh.validity, 1, aircraft.nav_qnh.value); try line.tagged("emergency", aircraft.emergency.validity, "{s}", .{json.emergencyName(aircraft.emergency.value)}); try line.tagged("mrar_source", aircraft.mrar_source.validity, "{s}", .{json.mrarSourceName(aircraft.mrar_source.value)}); try line.taggedFixed("wind_speed", aircraft.wind.validity, 0, aircraft.wind.value.speed); try line.taggedFixed("wind_dir", aircraft.wind.validity, 1, aircraft.wind.value.direction); try line.taggedFixed("temperature", aircraft.temperature.validity, 2, aircraft.temperature.value); try line.taggedFixed("pressure", aircraft.pressure.validity, 0, aircraft.pressure.value); try line.tagged("turbulence", aircraft.turbulence.validity, "{s}", .{json.hazardName(aircraft.turbulence.value)}); try line.taggedFixed("humidity", aircraft.humidity.validity, 0, aircraft.humidity.value);
if (w.end == before_data) { // Nothing current to say. Unwind the header rather than send a line // that is only an identifier. w.end = start_of_line; return false; }
// Replace the trailing tab with the newline. w.end -= 1; try w.writeByte('\n');
shadow.altitude_baro = aircraft.altitude_baro.value; shadow.altitude_geom = aircraft.altitude_geom.value; shadow.baro_rate = aircraft.baro_rate.value; shadow.geom_rate = aircraft.geom_rate.value; shadow.gs = aircraft.gs.value; shadow.ias = aircraft.ias.value; shadow.tas = aircraft.tas.value; shadow.mach = aircraft.mach.value; shadow.track = aircraft.track.value; shadow.track_rate = aircraft.track_rate.value; shadow.roll = aircraft.roll.value; shadow.mag_heading = aircraft.mag_heading.value; shadow.true_heading = aircraft.true_heading.value; shadow.airground = aircraft.airground.value; shadow.nav_altitude_mcp = aircraft.nav_altitude_mcp.value; shadow.nav_altitude_fms = aircraft.nav_altitude_fms.value; shadow.nav_altitude_src = aircraft.nav_altitude_src.value; shadow.nav_heading = aircraft.nav_heading.value; shadow.nav_modes = aircraft.nav_modes.value; shadow.nav_qnh = aircraft.nav_qnh.value; shadow.callsign = aircraft.callsign.value; shadow.address_type = aircraft.address_type; shadow.adsb_version = aircraft.adsb_version; shadow.category = aircraft.category orelse 0; shadow.squawk = aircraft.squawk.value; shadow.nac_p = aircraft.nac_p.value; shadow.nac_v = aircraft.nac_v.value; shadow.sil = aircraft.sil.value; shadow.sil_type = aircraft.sil_type; shadow.nic_baro = aircraft.nic_baro.value; shadow.emergency = aircraft.emergency.value; shadow.last_emitted = now_ms; if (force) shadow.last_force_emit = now_ms;
return true;}
const testing = std.testing;
/// A tracked aircraft with nothing recorded about it yet.fn bareAircraft(now: u64) track.Aircraft { return .{ .address = 0x4840d6, .address_type = .adsb_icao, .reliable = true, .seen = now, .fatsv = .{ .last_emitted = now, .last_force_emit = now }, };}
/// An aircraft that has just been created and heard from, as the tracker/// would have left it.fn testAircraft(now: u64) track.Aircraft { var a: track.Aircraft = .{ .address = 0x4840d6, .address_type = .adsb_icao, .reliable = true, .seen = now, .fatsv = .{ .last_emitted = now, .last_force_emit = now }, }; _ = a.altitude_baro.set(now, .adsb, 35000); _ = a.position.set(now, .adsb, .{ .position = .{ .latitude = 51.9, .longitude = 4.4 }, .nic = 8, .rc = 186, }); return a;}
fn renderLine(a: *track.Aircraft, now: u64, buf: []u8) !?[]const u8 { var w: Io.Writer = .fixed(buf); return if (try writeAircraft(&w, a, now, .{})) w.buffered() else null;}
test "a new aircraft waits its turn rather than reporting at once" { const start: u64 = 1_000_000; var a = testAircraft(start); var buf: [max_line]u8 = undefined;
// Nothing has changed in a way worth interrupting for, and no time has // passed, so there is nothing to send. try testing.expectEqual(@as(?[]const u8, null), try renderLine(&a, start, &buf));
// Above ten thousand feet the wait is ten seconds while something is // changing — and an altitude appearing where the last line had none // counts as a change. try testing.expectEqual(@as(?[]const u8, null), try renderLine(&a, start + 9_000, &buf)); try testing.expect(try renderLine(&a, start + 10_000, &buf) != null);}
test "an aircraft near the ground is reported every second" { const start: u64 = 1_000_000; var a = bareAircraft(start); _ = a.position.set(start, .adsb, .{ .position = .{ .latitude = 51.9, .longitude = 4.4 }, .nic = 8, .rc = 186, }); _ = a.airground.set(start, .mode_s_checked, .ground); // An altitude from a bare Mode S reply, which is the case the rule below // is about: an ADS-B one would be believed. _ = a.altitude_baro.set(start, .mode_s, 31000); var buf: [max_line]u8 = undefined;
try testing.expectEqual(@as(?[]const u8, null), try renderLine(&a, start + 900, &buf)); const line = (try renderLine(&a, start + 1000, &buf)).?; try testing.expect(std.mem.indexOf(u8, line, "airGround\tG+ 0 S\t") != null); // On the ground, an altitude that came from a bare Mode S reply is not // to be trusted and is withheld. try testing.expect(std.mem.indexOf(u8, line, "alt\t") == null);}
test "a change worth acting on interrupts the schedule" { const start: u64 = 1_000_000; var a = testAircraft(start); var buf: [max_line]u8 = undefined;
// A squawk that was not there before goes out immediately, well inside // the thirty seconds this aircraft would otherwise wait. a.seen = start + 1000; _ = a.squawk.set(start + 1000, .mode_s_checked, 0x7700); const line = (try renderLine(&a, start + 1000, &buf)).?; try testing.expect(std.mem.indexOf(u8, line, "squawk\t7700 0 S\t") != null);}
test "a line says who it is about and in what format" { const start: u64 = 1_000_000; var a = testAircraft(start); var buf: [max_line]u8 = undefined;
const line = (try renderLine(&a, start + 10_000, &buf)).?; try testing.expect(std.mem.startsWith(u8, line, "_v\t9E\tclock\t1000\thexid\t4840D6\t")); try testing.expect(std.mem.endsWith(u8, line, "\n")); // The address type is stated on the first line, since the shadow copy // starts out saying "unknown". try testing.expect(std.mem.indexOf(u8, line, "addrtype\tadsb_icao\t") != null); // A position carries its integrity and containment radius. try testing.expect(std.mem.indexOf(u8, line, "position\t{51.90000 4.40000 8 186} 0 A") != null);}
test "a fabricated address is otherid rather than hexid" { const start: u64 = 1_000_000; var a = testAircraft(start); a.address |= message.non_icao_address; var buf: [max_line]u8 = undefined;
const line = (try renderLine(&a, start + 10_000, &buf)).?; try testing.expect(std.mem.indexOf(u8, line, "otherid\t4840D6\t") != null); try testing.expect(std.mem.indexOf(u8, line, "hexid") == null);}
test "nothing this receiver merely inferred is forwarded" { const start: u64 = 1_000_000; var a = bareAircraft(start); // Multilateration is this receiver's arithmetic, not the aircraft's word. _ = a.altitude_baro.set(start, .mlat, 35000); _ = a.position.set(start, .mlat, .{ .position = .{ .latitude = 51.9, .longitude = 4.4 }, .nic = 8, .rc = 186, }); var buf: [max_line]u8 = undefined;
// Every field it had came from multilateration, so the line would carry // nothing and is not sent at all. try testing.expectEqual(@as(?[]const u8, null), try renderLine(&a, start + 60_000, &buf));}
test "an unreliable track is not reported" { const start: u64 = 1_000_000; var a = testAircraft(start); a.reliable = false; var buf: [max_line]u8 = undefined; try testing.expectEqual(@as(?[]const u8, null), try renderLine(&a, start + 60_000, &buf));}
test "the seldom-changing fields are re-sent every ten minutes" { const start: u64 = 1_000_000; var a = testAircraft(start); a.category = 0xa3; var buf: [max_line]u8 = undefined;
// The first line states them because the shadow copy starts empty. const first = (try renderLine(&a, start + 10_000, &buf)).?; try testing.expect(std.mem.indexOf(u8, first, "category\tA3\t") != null);
// The next does not: nothing about them changed. The aircraft has to // still be saying something, though, or there would be no line at all — // a field not heard since the last line is not repeated. a.seen = start + 60_000; _ = a.altitude_baro.set(start + 60_000, .adsb, 35000); var buf2: [max_line]u8 = undefined; const second = (try renderLine(&a, start + 60_000, &buf2)).?; try testing.expect(std.mem.indexOf(u8, second, "category") == null); try testing.expect(std.mem.indexOf(u8, second, "addrtype") == null);
// Ten minutes on, they go out again whether or not they changed. a.seen = start + 700_000; _ = a.altitude_baro.set(start + 700_000, .adsb, 35000); var buf3: [max_line]u8 = undefined; const third = (try renderLine(&a, start + 700_000, &buf3)).?; try testing.expect(std.mem.indexOf(u8, third, "category\tA3\t") != null); try testing.expect(std.mem.indexOf(u8, third, "addrtype\tadsb_icao\t") != null);}
test "the rate multiplier scales how often an aircraft is reported" { const start: u64 = 1_000_000; var a = testAircraft(start); var buf: [max_line]u8 = undefined;
// Twice as often means the thirty-second wait becomes fifteen. // Twice as often means the ten-second wait becomes five. var w: Io.Writer = .fixed(&buf); try testing.expect(!try writeAircraft(&w, &a, start + 4_000, .{ .rate_multiplier = 2 })); w = .fixed(&buf); try testing.expect(try writeAircraft(&w, &a, start + 5_000, .{ .rate_multiplier = 2 }));}