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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874// 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
//! The JSON files that feed the map.//!//! Every second or so the tracker's state is written out as//! `aircraft.json`, which the web interface polls. It is a snapshot rather//! than a stream: what each aircraft is now, with a `seen` telling the reader//! how stale that is.//!//! Two things about the shape are worth knowing. A field appears only if it//! is currently valid, so a reader has to treat every field as optional —//! which is also why `alt_baro` can be the *string* `"ground"` rather than a//! number. And the `mlat` and `tisb` arrays name which of the other fields//! came from those sources rather than from the aircraft directly, so that a//! map can show a multilateration position differently from a reported one.
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;
const fmt = @import("fmt.zig");const message = @import("message.zig");const stats_mod = @import("stats.zig");const track = @import("track.zig");const Aircraft = track.Aircraft;
/// Write a string as a JSON string body, escaping what has to be escaped.////// Everything outside printable ASCII is escaped, not just the characters/// JSON requires: a callsign can hold any of the six-bit alphabet's/// punctuation, and a receiver should not be able to put raw control/// characters into a file a browser will read.pub fn writeEscaped(w: *Io.Writer, text: []const u8) Io.Writer.Error!void { for (text) |ch| { switch (ch) { '"', '\\' => try w.print("\\{c}", .{ch}), 32...33, 35...91, 93...127 => try w.writeByte(ch), else => try w.print("\\u{x:0>4}", .{ch}), } }}
/// The name each address type goes by in the JSON.pub fn addressTypeName(kind: message.AddressType) []const u8 { return switch (kind) { .adsb_icao => "adsb_icao", .adsb_icao_nt => "adsb_icao_nt", .adsr_icao => "adsr_icao", .tisb_icao => "tisb_icao", .adsb_other => "adsb_other", .adsr_other => "adsr_other", .tisb_other => "tisb_other", .tisb_trackfile => "tisb_trackfile", .mode_a, .unknown => "unknown", };}
pub fn emergencyName(emergency: message.Emergency) []const u8 { return switch (emergency) { .none => "none", .general => "general", .lifeguard => "lifeguard", .min_fuel => "minfuel", .no_comms => "nordo", .unlawful_interference => "unlawful", .downed => "downed", .reserved => "reserved", };}
pub fn silTypeName(kind: message.SilType) []const u8 { return switch (kind) { .unknown => "unknown", .per_hour => "perhour", .per_sample => "persample", .invalid => "invalid", };}
pub fn mrarSourceName(source: message.MrarSource) []const u8 { return switch (source) { .invalid => "invalid", .ins => "ins", .gnss => "gnss", .dme_dme => "dmedme", .vor_dme => "vordme", .reserved => "reserved", };}
pub fn hazardName(hazard: message.Hazard) []const u8 { return switch (hazard) { .nil => "nil", .light => "light", .moderate => "moderate", .severe => "severe", };}
/// The autopilot modes, in the order the format lists them.const nav_mode_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" },};
fn writeNavModes(w: *Io.Writer, engaged: message.NavModes) Io.Writer.Error!void { var first = true; inline for (nav_mode_names) |mode| { if (@field(engaged, mode.field)) { if (!first) try w.writeByte(','); try w.print("\"{s}\"", .{mode.name}); first = false; } }}
/// Which of an aircraft's fields last came from a particular source.////// A map wants to draw a multilateration position differently from a/// reported one, and this is how it is told which is which.fn writeSourceFlags(w: *Io.Writer, a: *const Aircraft, source: message.Source) Io.Writer.Error!void { try w.writeByte('[');
var first = true; const fields = [_]struct { validity: track.Validity, names: []const u8 }{ .{ .validity = a.callsign.validity, .names = "\"callsign\"" }, .{ .validity = a.altitude_baro.validity, .names = "\"altitude\"" }, .{ .validity = a.altitude_geom.validity, .names = "\"alt_geom\"" }, .{ .validity = a.gs.validity, .names = "\"gs\"" }, .{ .validity = a.ias.validity, .names = "\"ias\"" }, .{ .validity = a.tas.validity, .names = "\"tas\"" }, .{ .validity = a.mach.validity, .names = "\"mach\"" }, .{ .validity = a.track.validity, .names = "\"track\"" }, .{ .validity = a.track_rate.validity, .names = "\"track_rate\"" }, .{ .validity = a.roll.validity, .names = "\"roll\"" }, .{ .validity = a.mag_heading.validity, .names = "\"mag_heading\"" }, .{ .validity = a.true_heading.validity, .names = "\"true_heading\"" }, .{ .validity = a.baro_rate.validity, .names = "\"baro_rate\"" }, .{ .validity = a.geom_rate.validity, .names = "\"geom_rate\"" }, .{ .validity = a.squawk.validity, .names = "\"squawk\"" }, .{ .validity = a.emergency.validity, .names = "\"emergency\"" }, .{ .validity = a.nav_qnh.validity, .names = "\"nav_qnh\"" }, .{ .validity = a.nav_altitude_mcp.validity, .names = "\"nav_altitude_mcp\"" }, .{ .validity = a.nav_altitude_fms.validity, .names = "\"nav_altitude_fms\"" }, .{ .validity = a.nav_heading.validity, .names = "\"nav_heading\"" }, .{ .validity = a.nav_modes.validity, .names = "\"nav_modes\"" }, .{ .validity = a.position.validity, .names = "\"lat\",\"lon\",\"nic\",\"rc\"" }, .{ .validity = a.nic_baro.validity, .names = "\"nic_baro\"" }, .{ .validity = a.nac_p.validity, .names = "\"nac_p\"" }, .{ .validity = a.nac_v.validity, .names = "\"nac_v\"" }, .{ .validity = a.sil.validity, .names = "\"sil\",\"sil_type\"" }, .{ .validity = a.gva.validity, .names = "\"gva\"" }, .{ .validity = a.sda.validity, .names = "\"sda\"" }, };
for (fields) |field| { if (field.validity.source != source) continue; if (!first) try w.writeByte(','); try w.writeAll(field.names); first = false; }
try w.writeByte(']');}
/// Write one aircraft's object.pub fn writeAircraft(w: *Io.Writer, a: *const Aircraft, now: u64) Io.Writer.Error!void { // A tilde marks an identifier that is not a real ICAO address, so that a // reader cannot mistake one for the other. try w.print("{{\"hex\":\"{s}{x:0>6}\"", .{ if (a.addressIsIcao()) "" else "~", a.address & 0xffffff, });
if (a.address_type != .adsb_icao) try w.print(",\"type\":\"{s}\"", .{addressTypeName(a.address_type)});
if (a.callsign.get(now)) |callsign| { try w.writeAll(",\"flight\":\""); try writeEscaped(w, &callsign); try w.writeByte('"'); }
// On the ground there is no altitude to report, and saying so is more // useful than leaving the field out — but only if the ground state came // from somewhere that could actually check it. const on_ground = a.airground.isValid(now) and @intFromEnum(a.airground.validity.source) >= @intFromEnum(message.Source.mode_s_checked) and a.airground.value == .ground;
if (on_ground) { try w.writeAll(",\"alt_baro\":\"ground\""); } else { if (a.altitude_baro.get(now)) |altitude| try w.print(",\"alt_baro\":{d}", .{altitude}); if (a.altitude_geom.get(now)) |altitude| try w.print(",\"alt_geom\":{d}", .{altitude}); }
if (a.gs.get(now)) |value| try writeFixed(w, ",\"gs\":", 1, value); if (a.ias.get(now)) |value| try w.print(",\"ias\":{d}", .{value}); if (a.tas.get(now)) |value| try w.print(",\"tas\":{d}", .{value}); if (a.mach.get(now)) |value| try writeFixed(w, ",\"mach\":", 3, value); if (a.track.get(now)) |value| try writeFixed(w, ",\"track\":", 1, value); if (a.track_rate.get(now)) |value| try writeFixed(w, ",\"track_rate\":", 2, value); if (a.roll.get(now)) |value| try writeFixed(w, ",\"roll\":", 1, value); if (a.mag_heading.get(now)) |value| try writeFixed(w, ",\"mag_heading\":", 1, value); if (a.true_heading.get(now)) |value| try writeFixed(w, ",\"true_heading\":", 1, value); if (a.baro_rate.get(now)) |value| try w.print(",\"baro_rate\":{d}", .{value}); if (a.geom_rate.get(now)) |value| try w.print(",\"geom_rate\":{d}", .{value}); if (a.squawk.get(now)) |value| try w.print(",\"squawk\":\"{x:0>4}\"", .{value}); if (a.emergency.get(now)) |value| try w.print(",\"emergency\":\"{s}\"", .{emergencyName(value)}); if (a.category) |category| try w.print(",\"category\":\"{X:0>2}\"", .{category});
if (a.nav_qnh.get(now)) |value| try writeFixed(w, ",\"nav_qnh\":", 1, value); if (a.nav_altitude_mcp.get(now)) |value| try w.print(",\"nav_altitude_mcp\":{d}", .{value}); if (a.nav_altitude_fms.get(now)) |value| try w.print(",\"nav_altitude_fms\":{d}", .{value}); if (a.nav_heading.get(now)) |value| try writeFixed(w, ",\"nav_heading\":", 1, value); if (a.nav_modes.get(now)) |engaged| { try w.writeAll(",\"nav_modes\":["); try writeNavModes(w, engaged); try w.writeByte(']'); }
if (a.position.get(now)) |fix| { try writeFixed(w, ",\"lat\":", 6, fix.position.latitude); try writeFixed(w, ",\"lon\":", 6, fix.position.longitude); try w.print(",\"nic\":{d},\"rc\":{d}", .{ fix.nic, fix.rc }); try writeFixed(w, ",\"seen_pos\":", 1, elapsedSeconds(now, a.position.validity.updated)); }
if (a.adsb_version) |version| try w.print(",\"version\":{d}", .{version});
if (a.nic_baro.get(now)) |value| try w.print(",\"nic_baro\":{d}", .{value}); if (a.nac_p.get(now)) |value| try w.print(",\"nac_p\":{d}", .{value}); if (a.nac_v.get(now)) |value| try w.print(",\"nac_v\":{d}", .{value}); if (a.sil.get(now)) |value| try w.print(",\"sil\":{d}", .{value}); if (a.sil_type != .invalid) try w.print(",\"sil_type\":\"{s}\"", .{silTypeName(a.sil_type)}); if (a.gva.get(now)) |value| try w.print(",\"gva\":{d}", .{value}); if (a.sda.get(now)) |value| try w.print(",\"sda\":{d}", .{value});
if (a.mrar_source.get(now)) |source| try w.print(",\"mrar_source\":\"{s}\"", .{mrarSourceName(source)}); if (a.wind.get(now)) |wind| { try writeFixed(w, ",\"wind_speed\":", 0, wind.speed); try writeFixed(w, ",\"wind_dir\":", 1, wind.direction); } if (a.temperature.get(now)) |value| try writeFixed(w, ",\"temperature\":", 2, value); if (a.pressure.get(now)) |value| try writeFixed(w, ",\"pressure\":", 0, value); if (a.turbulence.get(now)) |value| try w.print(",\"turbulence\":\"{s}\"", .{hazardName(value)}); if (a.humidity.get(now)) |value| try writeFixed(w, ",\"humidity\":", 1, value);
if (a.mode_a_hit) try w.writeAll(",\"modea\":true"); if (a.mode_c_hit) try w.writeAll(",\"modec\":true");
try w.writeAll(",\"mlat\":"); try writeSourceFlags(w, a, .mlat); try w.writeAll(",\"tisb\":"); try writeSourceFlags(w, a, .tisb);
try w.print(",\"messages\":{d}", .{a.messages}); try writeFixed(w, ",\"seen\":", 1, elapsedSeconds(now, a.seen)); // The mean of the last eight signal levels, in decibels relative to full // scale. The small constant keeps the logarithm finite when every one of // them is zero. try writeFixed(w, ",\"rssi\":", 1, 10 * @log10(a.meanSignalLevel() + 1e-5 / 8.0)); try w.writeByte('}');}
/// Write the whole `aircraft.json` file.////// `message_count` is the running total of messages received, which the map/// shows as a rate.pub fn writeAircraftFile(w: *Io.Writer, tracker: *const track.Tracker, now: u64, message_count: u64) Io.Writer.Error!void { try w.writeAll("{ \"now\" : "); try fmt.fixed(w, 1, @as(f64, @floatFromInt(now)) / 1000.0); try w.print(",\n \"messages\" : {d},\n \"aircraft\" : [", .{message_count});
var first = true; var it = tracker.iterator(); while (it.next()) |aircraft| { // Aircraft nothing believes in are noise that decoded; showing them // would fill the map with ghosts. if (!aircraft.reliable) continue;
if (!first) try w.writeByte(','); first = false;
try w.writeAll("\n "); try writeAircraft(w, aircraft, now); }
try w.writeAll("\n ]\n}\n");}
/// Write one window of statistics as a JSON object body.pub fn writeStats( w: *Io.Writer, key: []const u8, st: stats_mod.Stats, options: stats_mod.Options,) Io.Writer.Error!void { try w.print("\"{s}\":{{", .{key}); try writeFixed(w, "\"start\":", 1, @as(f64, @floatFromInt(st.start)) / 1000.0); try writeFixed(w, ",\"end\":", 1, @as(f64, @floatFromInt(st.end)) / 1000.0);
if (options.local) { try w.print( ",\"local\":{{\"samples_processed\":{d},\"samples_dropped\":{d}" ++ ",\"modeac\":{d},\"modes\":{d},\"bad\":{d},\"unknown_icao\":{d}", .{ st.samples_processed, st.samples_dropped, st.demod_modeac, st.demod_preambles, st.demod_rejected_bad, st.demod_rejected_unknown_icao, }, ); try writeCounts(w, ",\"accepted\":", st.demod_accepted[0 .. correctionLevels(options.fix_bits) + 1]);
if (st.signalDbfs()) |value| try writeFixed(w, ",\"signal\":", 1, value); if (st.noiseDbfs()) |value| try writeFixed(w, ",\"noise\":", 1, value); if (st.peakDbfs()) |value| try writeFixed(w, ",\"peak_signal\":", 1, value);
try w.print(",\"strong_signals\":{d}", .{st.strong_signal_count}); try w.writeByte('}'); }
if (options.net) { try w.print( ",\"remote\":{{\"modeac\":{d},\"modes\":{d},\"bad\":{d},\"unknown_icao\":{d}", .{ st.remote_received_modeac, st.remote_received_modes, st.remote_rejected_bad, st.remote_rejected_unknown_icao, }, ); try writeCounts(w, ",\"accepted\":", st.remote_accepted[0 .. correctionLevels(options.fix_bits) + 1]); try w.writeByte('}'); }
try w.print( ",\"cpr\":{{\"surface\":{d},\"airborne\":{d},\"global_ok\":{d},\"global_bad\":{d}" ++ ",\"global_range\":{d},\"global_speed\":{d},\"global_skipped\":{d}" ++ ",\"local_ok\":{d},\"local_aircraft_relative\":{d},\"local_receiver_relative\":{d}" ++ ",\"local_skipped\":{d},\"local_range\":{d},\"local_speed\":{d},\"filtered\":{d}}}" ++ ",\"altitude_suppressed\":{d}" ++ ",\"cpu\":{{\"demod\":{d},\"reader\":{d},\"background\":{d}}}" ++ ",\"tracks\":{{\"all\":{d},\"single_message\":{d},\"unreliable\":{d}}}" ++ ",\"messages\":{d}", .{ st.cpr_surface, st.cpr_airborne, st.cpr_global_ok, st.cpr_global_bad, st.cpr_global_range_checks, st.cpr_global_speed_checks, st.cpr_global_skipped, st.cpr_local_ok, st.cpr_local_aircraft_relative, st.cpr_local_receiver_relative, st.cpr_local_skipped, st.cpr_local_range_checks, st.cpr_local_speed_checks, st.cpr_filtered, st.suppressed_altitude_messages, st.demod_cpu_ms, st.reader_cpu_ms, st.background_cpu_ms, st.unique_aircraft, st.single_message_aircraft, st.unreliable_aircraft, st.messages_total, }, );
try writeCounts(w, ",\"messages_by_df\":", &st.messages_by_df);
if (st.adaptive_valid) { try writeFixed(w, ",\"adaptive\":{\"gain_db\":", 1, stats_mod.gainDbAt(options, st.sdr_gain orelse 0)); try writeFixed(w, ",\"dynamic_range_limit_db\":", 1, stats_mod.gainDbAt(options, st.adaptive_range_gain_limit orelse 0)); try w.print(",\"gain_changes\":{d},\"loud_undecoded\":{d},\"loud_decoded\":{d}", .{ st.adaptive_gain_changes, st.adaptive_loud_undecoded, st.adaptive_loud_decoded, }); try writeFixed(w, ",\"noise_dbfs\":", 1, st.adaptive_noise_dbfs);
// Only the steps that were actually used, each as a [decibels, // seconds] pair, so that a tuner with fifty steps does not write // fifty zeroes every minute. try w.writeAll(",\"gain_seconds\":["); var first = true; for (st.adaptive_gain_seconds, 0..) |seconds, step| { if (seconds == 0) continue; if (!first) try w.writeByte(','); first = false; try writeFixed(w, "[", 1, stats_mod.gainDbAt(options, @intCast(step))); try w.print(",{d}]", .{seconds}); } try w.writeAll("]}"); }
try w.writeByte('}');}
/// Write a JSON array of counts.fn writeCounts(w: *Io.Writer, prefix: []const u8, counts: []const u64) Io.Writer.Error!void { try w.writeAll(prefix); try w.writeByte('['); for (counts, 0..) |count, i| { if (i != 0) try w.writeByte(','); try w.print("{d}", .{count}); } try w.writeByte(']');}
fn correctionLevels(fix_bits: @import("crc.zig").FixBits) usize { return switch (fix_bits) { .none => 0, .one => 1, .two => 2, };}
/// Write the whole `stats.json`, which is every window at once.////// Flushes the windows first: what has accumulated since the last minute/// rolled over is part of `latest` and of the running total, and a reader/// polling this file would otherwise see a minute-old picture.pub fn writeStatsFile(w: *Io.Writer, windows: *stats_mod.Windows, options: stats_mod.Options) Io.Writer.Error!void { windows.flush();
try w.writeByte('{'); try writeStats(w, "latest", windows.latest, options); try w.writeByte(','); try writeStats(w, "last1min", windows.one_minute[windows.newest], options); try w.writeByte(','); try writeStats(w, "last5min", windows.five_minute, options); try w.writeByte(','); try writeStats(w, "last15min", windows.fifteen_minute, options); try w.writeByte(','); try writeStats(w, "total", windows.alltime, options); try w.writeAll("}\n");}
/// Where the antenna is, as the receiver metadata reports it.pub const Position = struct { latitude: f64, longitude: f64 };
/// How accurately the receiver's own position is published.pub const LocationAccuracy = enum(u2) { /// Do not publish it at all. none = 0, /// Round to two decimal places, about a kilometre, so that the map can /// centre itself without giving away an address. approximate = 1, /// Exactly where the antenna is. exact = 2,};
/// Write `receiver.json`, which tells the map how to talk to this receiver.pub fn writeReceiverFile( w: *Io.Writer, version: []const u8, refresh_ms: u64, history_count: usize, position: ?Position, accuracy: LocationAccuracy,) Io.Writer.Error!void { try w.print("{{ \"version\" : \"{s}\", \"refresh\" : {d}, \"history\" : {d}", .{ version, refresh_ms, history_count, });
if (accuracy != .none) { if (position) |at| { if (at.latitude != 0.0 or at.longitude != 0.0) { const decimals: comptime_int = 6; if (accuracy == .approximate) { try writeFixed(w, ", \"lat\" : ", 2, at.latitude); try writeFixed(w, ", \"lon\" : ", 2, at.longitude); } else { try writeFixed(w, ", \"lat\" : ", decimals, at.latitude); try writeFixed(w, ", \"lon\" : ", decimals, at.longitude); } } } }
try w.writeAll(" }\n");}
fn writeFixed(w: *Io.Writer, prefix: []const u8, comptime decimals: comptime_int, value: f64) Io.Writer.Error!void { try w.writeAll(prefix); try fmt.fixed(w, decimals, value);}
/// Seconds between two millisecond timestamps, never negative.////// A message can be stamped a few milliseconds ahead of the moment the file/// is written, because its timestamp comes from the sample block it arrived/// in rather than from the clock. Upstream subtracts anyway, and an unsigned/// underflow turns "just now" into `18446744073709552.0` seconds — which a/// map reads as an aircraft last seen six hundred million years ago and/// hides. Saturating is the only sane answer, so this is a deliberate/// departure.fn elapsedSeconds(now: u64, then: u64) f64 { return @as(f64, @floatFromInt(now -| then)) / 1000.0;}
/// How many snapshots of the aircraft list are kept, and how far apart.////// An hour of history at half-minute intervals, which is what the map's/// trail lines are drawn from. It is kept as whole files rather than as a/// list of positions because that is what the map fetches: one request per/// snapshot, cached by the browser, with no server-side query at all.pub const history_size = 120;pub const history_interval_ms = 30_000;
/// Writes the JSON files periodically, so the map has something to poll.////// Each file is written to a temporary name and renamed into place, so a/// reader never sees a half-written one. That matters more than it sounds:/// the map polls once a second and a torn read is a page full of errors.pub const Writer = struct { gpa: Allocator, directory: Io.Dir, /// How often `aircraft.json` is rewritten. interval_ms: u64, /// When it is next due. next_write_ms: u64 = 0,
/// Which history slot is next to be written. history_next: usize = 0, /// How many slots have been filled, up to `history_size`. history_filled: usize = 0, /// When the next snapshot is due. next_history_ms: u64 = 0,
/// The text being built, reused between writes. buffer: std.ArrayList(u8) = .empty,
pub const OpenError = Io.Dir.OpenError;
pub fn init(gpa: Allocator, io: Io, path: []const u8, interval_ms: u64) OpenError!Writer { return .{ .gpa = gpa, .directory = try Io.Dir.cwd().openDir(io, path, .{}), .interval_ms = interval_ms, }; }
pub fn deinit(self: *Writer, io: Io) void { self.buffer.deinit(self.gpa); self.directory.close(io); self.* = undefined; }
/// How many history snapshots exist, which `receiver.json` publishes so /// that the map knows how many to ask for. pub fn historyCount(self: *const Writer) usize { return self.history_filled; }
/// Take a history snapshot if one is due. Returns whether the count of /// snapshots changed, which means `receiver.json` needs rewriting. pub fn periodicHistory( self: *Writer, io: Io, tracker: *const track.Tracker, now: u64, message_count: u64, ) !bool { if (now < self.next_history_ms) return false; self.next_history_ms = now + history_interval_ms;
self.buffer.clearRetainingCapacity(); var w = std.Io.Writer.Allocating.fromArrayList(self.gpa, &self.buffer); defer self.buffer = w.toArrayList();
try writeAircraftFile(&w.writer, tracker, now, message_count);
var name_buf: [32]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "history_{d}.json", .{self.history_next}); try self.replace(io, name, w.writer.buffered());
self.history_next = (self.history_next + 1) % history_size;
// Once the ring has wrapped the count stops changing, and // `receiver.json` no longer needs rewriting. if (self.history_filled < history_size) { self.history_filled += 1; return true; } return false; }
/// Rewrite `stats.json`. pub fn writeStatsSnapshot( self: *Writer, io: Io, windows: *stats_mod.Windows, options: stats_mod.Options, ) !void { self.buffer.clearRetainingCapacity(); var w = std.Io.Writer.Allocating.fromArrayList(self.gpa, &self.buffer); defer self.buffer = w.toArrayList();
try writeStatsFile(&w.writer, windows, options); try self.replace(io, "stats.json", w.writer.buffered()); }
/// Rewrite `aircraft.json` if it is due. Returns whether it did. pub fn periodic( self: *Writer, io: Io, tracker: *const track.Tracker, now: u64, message_count: u64, ) !bool { if (now < self.next_write_ms) return false; self.next_write_ms = now + self.interval_ms;
self.buffer.clearRetainingCapacity(); var w = std.Io.Writer.Allocating.fromArrayList(self.gpa, &self.buffer); defer self.buffer = w.toArrayList();
try writeAircraftFile(&w.writer, tracker, now, message_count); try self.replace(io, "aircraft.json", w.writer.buffered()); return true; }
/// Write `receiver.json`, which changes only when the configuration does. pub fn writeReceiver( self: *Writer, io: Io, version: []const u8, position: ?Position, accuracy: LocationAccuracy, ) !void { self.buffer.clearRetainingCapacity(); var w = std.Io.Writer.Allocating.fromArrayList(self.gpa, &self.buffer); defer self.buffer = w.toArrayList();
try writeReceiverFile(&w.writer, version, self.interval_ms, self.history_filled, position, accuracy); try self.replace(io, "receiver.json", w.writer.buffered()); }
/// Put `contents` at `name`, atomically. fn replace(self: *Writer, io: Io, name: []const u8, contents: []const u8) !void { var temporary_name_buf: [64]u8 = undefined; const temporary_name = try std.fmt.bufPrint(&temporary_name_buf, "{s}.new", .{name});
{ const file = try self.directory.createFile(io, temporary_name, .{}); defer file.close(io);
var buffer: [4096]u8 = undefined; var file_writer = file.writer(io, &buffer); try file_writer.interface.writeAll(contents); try file_writer.interface.flush(); }
try Io.Dir.rename(self.directory, temporary_name, self.directory, name, io); }};
const testing = std.testing;
/// Render one aircraft and hand back the text.fn renderAircraft(a: *const Aircraft, now: u64, buf: []u8) ![]const u8 { var w: Io.Writer = .fixed(buf); try writeAircraft(&w, a, now); return w.buffered();}
test "string escaping" { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try writeEscaped(&w, "KLM1023 "); try testing.expectEqualStrings("KLM1023 ", w.buffered());
w = .fixed(&buf); try writeEscaped(&w, "a\"b\\c"); try testing.expectEqualStrings("a\\\"b\\\\c", w.buffered());
// Control characters are escaped, so that a misbehaving transponder // cannot put them into a file a browser will read. Delete is not, which // is where upstream's bound happens to fall. w = .fixed(&buf); try writeEscaped(&w, "a\x01b\x7f"); try testing.expectEqualStrings("a\\u0001b\x7f", w.buffered());}
test "an aircraft with nothing known is still an object" { var a: Aircraft = .{ .address = 0x4840d6, .address_type = .adsb_icao }; a.messages = 1;
var buf: [4096]u8 = undefined; const text = try renderAircraft(&a, 1000, &buf);
try testing.expectEqualStrings( "{\"hex\":\"4840d6\",\"mlat\":[],\"tisb\":[],\"messages\":1,\"seen\":1.0,\"rssi\":-49.5}", text, );}
test "a non-ICAO address is marked with a tilde" { var a: Aircraft = .{ .address = 0x4840d6 | message.non_icao_address, .address_type = .tisb_trackfile, };
var buf: [4096]u8 = undefined; const text = try renderAircraft(&a, 0, &buf);
try testing.expect(std.mem.startsWith(u8, text, "{\"hex\":\"~4840d6\",\"type\":\"tisb_trackfile\""));}
test "a full aircraft" { var a: Aircraft = .{ .address = 0x4840d6, .address_type = .adsb_icao }; a.messages = 42; a.seen = 9500; a.category = 0xa3; a.adsb_version = 2; a.sil_type = .per_hour; a.signal_level = @splat(0.01);
_ = a.callsign.set(10000, .adsb, "KLM1023 ".*); _ = a.altitude_baro.set(10000, .adsb, 38000); _ = a.altitude_geom.set(10000, .adsb, 38300); _ = a.gs.set(10000, .adsb, 450.25); _ = a.track.set(10000, .adsb, 275.5); _ = a.baro_rate.set(10000, .adsb, -1024); _ = a.squawk.set(10000, .mode_s, 0x7700); _ = a.emergency.set(10000, .adsb, .general); _ = a.nav_modes.set(10000, .adsb, .{ .autopilot = true, .lnav = true }); _ = a.position.set(10000, .adsb, .{ .position = .{ .latitude = 52.2572, .longitude = 3.91937 }, .nic = 8, .rc = 186, }); _ = a.nac_p.set(10000, .adsb, 9); _ = a.sil.set(10000, .adsb, 3);
var buf: [4096]u8 = undefined; const text = try renderAircraft(&a, 10000, &buf);
try testing.expectEqualStrings( "{\"hex\":\"4840d6\",\"flight\":\"KLM1023 \"" ++ ",\"alt_baro\":38000,\"alt_geom\":38300,\"gs\":450.2,\"track\":275.5" ++ ",\"baro_rate\":-1024,\"squawk\":\"7700\",\"emergency\":\"general\"" ++ ",\"category\":\"A3\",\"nav_modes\":[\"autopilot\",\"lnav\"]" ++ ",\"lat\":52.257200,\"lon\":3.919370,\"nic\":8,\"rc\":186,\"seen_pos\":0.0" ++ ",\"version\":2,\"nac_p\":9,\"sil\":3,\"sil_type\":\"perhour\"" ++ ",\"mlat\":[],\"tisb\":[],\"messages\":42,\"seen\":0.5,\"rssi\":-20.0}", text, );}
test "an aircraft on the ground reports no altitude" { var a: Aircraft = .{ .address = 0x4840d6, .address_type = .adsb_icao }; _ = a.altitude_baro.set(1000, .adsb, 0);
// A ground state from a source that could not check it does not count. _ = a.airground.set(1000, .mode_s, .ground); var buf: [4096]u8 = undefined; try testing.expect(std.mem.indexOf(u8, try renderAircraft(&a, 1000, &buf), "\"alt_baro\":0") != null);
// From one that could, it does. _ = a.airground.set(2000, .adsb, .ground); const text = try renderAircraft(&a, 2000, &buf); try testing.expect(std.mem.indexOf(u8, text, "\"alt_baro\":\"ground\"") != null);}
test "source flags say which fields came from where" { var a: Aircraft = .{ .address = 0x4840d6, .address_type = .adsb_icao }; _ = a.altitude_baro.set(1000, .mlat, 38000); _ = a.position.set(1000, .mlat, .{ .position = .{ .latitude = 0, .longitude = 0 }, .nic = 0, .rc = 0, }); _ = a.callsign.set(1000, .tisb, "KLM1023 ".*);
var buf: [4096]u8 = undefined; const text = try renderAircraft(&a, 1000, &buf);
try testing.expect(std.mem.indexOf(u8, text, "\"mlat\":[\"altitude\",\"lat\",\"lon\",\"nic\",\"rc\"]") != null); try testing.expect(std.mem.indexOf(u8, text, "\"tisb\":[\"callsign\"]") != null);}
test "the whole file, with an unreliable aircraft left out" { var tracker: track.Tracker = .init(testing.allocator, .{}); defer tracker.deinit();
// Two aircraft, one of which the tracker does not believe in. for ([_]u32{ 0x100001, 0x100002 }) |address| { var mm: message.Message = .empty; mm.format = .{ .mode_s = 17 }; mm.address = address; mm.source = .adsb; mm.system_timestamp_ms = 1000; mm.reliable = true; for (0..if (address == 0x100001) @as(usize, 2) else 1) |_| { mm.system_timestamp_ms += 1; _ = try tracker.update(&mm); } }
var buf: [8192]u8 = undefined; var w: Io.Writer = .fixed(&buf); try writeAircraftFile(&w, &tracker, 5000, 123);
const text = w.buffered(); try testing.expect(std.mem.startsWith(u8, text, "{ \"now\" : 5.0,\n \"messages\" : 123,\n \"aircraft\" : [")); try testing.expect(std.mem.endsWith(u8, text, "\n ]\n}\n")); try testing.expect(std.mem.indexOf(u8, text, "\"hex\":\"100001\"") != null); try testing.expect(std.mem.indexOf(u8, text, "\"hex\":\"100002\"") == null);}
test "the receiver file" { var buf: [512]u8 = undefined;
var w: Io.Writer = .fixed(&buf); try writeReceiverFile(&w, "11.1", 1000, 120, null, .exact); try testing.expectEqualStrings("{ \"version\" : \"11.1\", \"refresh\" : 1000, \"history\" : 120 }\n", w.buffered());
// An approximate position is rounded to about a kilometre, so that a map // can centre itself without publishing an address. w = .fixed(&buf); try writeReceiverFile(&w, "11.1", 1000, 120, .{ .latitude = 52.257231, .longitude = 3.919371 }, .approximate); try testing.expect(std.mem.indexOf(u8, w.buffered(), "\"lat\" : 52.26, \"lon\" : 3.92") != null);
w = .fixed(&buf); try writeReceiverFile(&w, "11.1", 1000, 120, .{ .latitude = 52.257231, .longitude = 3.919371 }, .exact); try testing.expect(std.mem.indexOf(u8, w.buffered(), "\"lat\" : 52.257231, \"lon\" : 3.919371") != null);
// And with the position withheld, nothing is said about it at all. w = .fixed(&buf); try writeReceiverFile(&w, "11.1", 1000, 120, .{ .latitude = 52.257231, .longitude = 3.919371 }, .none); try testing.expect(std.mem.indexOf(u8, w.buffered(), "lat") == null);}
test "the statistics file has every window" { var windows: stats_mod.Windows = .{}; var cumulative: stats_mod.Stats = .empty; cumulative.messages_total = 42; cumulative.demod_preambles = 100; windows.update(cumulative, 60_000); windows.flush();
var buf: [8192]u8 = undefined; var w: Io.Writer = .fixed(&buf); try writeStatsFile(&w, &windows, .{ .fix_bits = .one });
const text = w.buffered(); for ([_][]const u8{ "latest", "last1min", "last5min", "last15min", "total" }) |key| { try testing.expect(std.mem.indexOf(u8, text, key) != null); } try testing.expect(std.mem.indexOf(u8, text, "\"messages\":42") != null); try testing.expect(std.mem.indexOf(u8, text, "\"modes\":100") != null); // One level of correction was enabled, so the array has two entries. try testing.expect(std.mem.indexOf(u8, text, "\"accepted\":[0,0]") != null); try testing.expect(std.mem.endsWith(u8, text, "}\n"));}
test "the local and remote sections appear only when they apply" { const windows: stats_mod.Windows = .{};
var buf: [8192]u8 = undefined; var w: Io.Writer = .fixed(&buf); try writeStats(&w, "total", windows.alltime, .{ .local = false, .net = true }); const remote_only = w.buffered(); try testing.expect(std.mem.indexOf(u8, remote_only, "\"local\"") == null); try testing.expect(std.mem.indexOf(u8, remote_only, "\"remote\"") != null);
w = .fixed(&buf); try writeStats(&w, "total", windows.alltime, .{ .local = true, .net = false }); const local_only = w.buffered(); try testing.expect(std.mem.indexOf(u8, local_only, "\"local\"") != null); try testing.expect(std.mem.indexOf(u8, local_only, "\"remote\"") == null);}