// 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 //! What the receiver has been doing. //! //! These counters are how a receiver is diagnosed from a distance. A rate of //! messages says nothing on its own — the useful questions are what fraction //! of preambles turned into messages, how far the noise floor is below the //! signals, and whether positions are being rejected by the range or speed //! checks. So the counters are kept at every stage of the pipeline and //! reported together. //! //! They are accumulated over several windows at once: the current one, the //! last full minute, the last five and fifteen minutes, and since the process //! started. Adding two windows together is how those are maintained, which is //! why `add` exists and why every field has to be summable. const std = @import("std"); const Io = std.Io; const datetime = @import("datetime"); const crc = @import("crc.zig"); const fmt = @import("fmt.zig"); /// Buckets in the range histogram. pub const range_bucket_count = 76; /// Gain steps the adaptive gain histogram covers. pub const gain_step_count = 64; /// Everything counted over one window of time. pub const Stats = struct { /// When the window began and ended, in milliseconds. start: u64 = 0, end: u64 = 0, // ---- The demodulator ---- /// Candidate preambles that passed the pattern checks. demod_preambles: u64 = 0, /// Candidates thrown away as implausible. demod_rejected_bad: u64 = 0, /// Candidates that looked like messages but named an unknown aircraft. demod_rejected_unknown_icao: u64 = 0, /// Messages accepted, by how many bits had to be corrected. demod_accepted: [crc.max_bit_errors + 1]u64 = @splat(0), /// Mode A/C replies demodulated. demod_modeac: u64 = 0, samples_processed: u64 = 0, samples_dropped: u64 = 0, /// The gain step in use, or null if the radio has no gain control. sdr_gain: ?u8 = null, // ---- Signal levels ---- /// The power of everything that was not a message, and how many samples /// that was: together, the noise floor. noise_power_sum: f64 = 0, noise_power_count: u64 = 0, /// The same for everything that was. signal_power_sum: f64 = 0, signal_power_count: u64 = 0, /// The strongest message seen. peak_signal_power: f64 = 0, /// Messages above -3 dBFS, where the receiver starts to clip. strong_signal_count: u64 = 0, // ---- Messages from other receivers ---- remote_received_modeac: u64 = 0, remote_received_modes: u64 = 0, remote_rejected_bad: u64 = 0, remote_rejected_unknown_icao: u64 = 0, remote_accepted: [crc.max_bit_errors + 1]u64 = @splat(0), // ---- The decoder ---- messages_total: u64 = 0, messages_by_df: [32]u64 = @splat(0), // ---- Position decoding ---- cpr_surface: u64 = 0, cpr_airborne: u64 = 0, cpr_global_ok: u64 = 0, cpr_global_bad: u64 = 0, cpr_global_skipped: u64 = 0, cpr_global_range_checks: u64 = 0, cpr_global_speed_checks: u64 = 0, cpr_local_ok: u64 = 0, cpr_local_skipped: u64 = 0, cpr_local_range_checks: u64 = 0, cpr_local_speed_checks: u64 = 0, cpr_local_aircraft_relative: u64 = 0, cpr_local_receiver_relative: u64 = 0, /// Position messages dropped by the transponder-failure filter. cpr_filtered: u64 = 0, /// Altitudes ignored because a better one had just arrived. suppressed_altitude_messages: u64 = 0, // ---- Aircraft ---- unique_aircraft: u64 = 0, single_message_aircraft: u64 = 0, unreliable_aircraft: u64 = 0, /// How many receptions fell in each range bucket. range_histogram: [range_bucket_count]u64 = @splat(0), // ---- Processor time, in milliseconds ---- demod_cpu_ms: u64 = 0, reader_cpu_ms: u64 = 0, background_cpu_ms: u64 = 0, // ---- Adaptive gain ---- /// Whether the adaptive gain figures below mean anything. adaptive_valid: bool = false, /// Seconds spent at each gain step. adaptive_gain_seconds: [gain_step_count]u64 = @splat(0), adaptive_loud_undecoded: u64 = 0, adaptive_loud_decoded: u64 = 0, adaptive_gain_changes: u64 = 0, adaptive_noise_dbfs: f64 = 0, adaptive_range_gain_limit: ?i32 = null, pub const empty: Stats = .{}; /// Add `other` into this window. /// /// Every numeric field sums; the window spans the union of the two, and /// the peak is the higher of the two peaks. Done reflectively so that a /// counter added to the struct cannot be forgotten here. pub fn add(self: *Stats, other: Stats) void { inline for (@typeInfo(Stats).@"struct".fields) |field| { const name = field.name; const value = &@field(self, name); const addend = @field(other, name); if (comptime std.mem.eql(u8, name, "start")) { // The earlier of the two, ignoring an unset window. value.* = if (value.* == 0) addend else if (addend == 0) value.* else @min(value.*, addend); } else if (comptime std.mem.eql(u8, name, "end")) { value.* = @max(value.*, addend); } else if (comptime std.mem.eql(u8, name, "peak_signal_power")) { value.* = @max(value.*, addend); } else if (comptime std.mem.eql(u8, name, "sdr_gain") or std.mem.eql(u8, name, "adaptive_range_gain_limit")) { // A setting rather than a count: the later window's wins. if (addend != null) value.* = addend; } else if (comptime std.mem.eql(u8, name, "adaptive_valid")) { value.* = value.* or addend; } else switch (@typeInfo(field.type)) { .int, .float => value.* += addend, .array => for (value, addend) |*slot, item| { slot.* += item; }, else => @compileError("stats field " ++ name ++ " has no rule for adding"), } } } /// Empty the window, keeping nothing. pub fn reset(self: *Stats) void { self.* = .empty; } /// Subtract `other`, which is how a cumulative total becomes the change /// since the last one was taken. /// /// Saturating, because a counter that was reset underneath us should /// produce zero rather than an enormous number. pub fn subtract(self: *Stats, other: Stats) void { inline for (@typeInfo(Stats).@"struct".fields) |field| { const name = field.name; if (comptime std.mem.eql(u8, name, "start") or std.mem.eql(u8, name, "end") or std.mem.eql(u8, name, "sdr_gain") or std.mem.eql(u8, name, "adaptive_valid") or std.mem.eql(u8, name, "adaptive_noise_dbfs") or std.mem.eql(u8, name, "adaptive_range_gain_limit") or std.mem.eql(u8, name, "peak_signal_power")) continue; const value = &@field(self, name); const amount = @field(other, name); switch (@typeInfo(field.type)) { .int => value.* -|= amount, .float => value.* = @max(value.* - amount, 0), .array => for (value, amount) |*slot, item| { slot.* -|= item; }, else => @compileError("stats field " ++ name ++ " has no rule for subtracting"), } } } /// The mean noise floor in decibels relative to full scale, or null if /// nothing was measured. pub fn noiseDbfs(self: Stats) ?f64 { if (self.noise_power_sum <= 0 or self.noise_power_count == 0) return null; return 10 * @log10(self.noise_power_sum / @as(f64, @floatFromInt(self.noise_power_count))); } /// The mean signal power, the same way. pub fn signalDbfs(self: Stats) ?f64 { if (self.signal_power_sum <= 0 or self.signal_power_count == 0) return null; return 10 * @log10(self.signal_power_sum / @as(f64, @floatFromInt(self.signal_power_count))); } /// The strongest message seen, the same way. pub fn peakDbfs(self: Stats) ?f64 { if (self.peak_signal_power <= 0) return null; return 10 * @log10(self.peak_signal_power); } }; /// Processor time used by one task, accumulated across the whole run. /// /// Reported because it is the number that says whether a receiver is keeping /// up. A Raspberry Pi demodulating 2.4 million samples a second has very /// little headroom, and the first symptom of running out is dropped samples /// rather than anything that looks like an error. pub const CpuTimer = struct { /// The clock reading at the last `start`. since: ?Io.Timestamp = null, /// Nanoseconds accumulated so far. total_ns: i128 = 0, /// Begin a measurement. Reading a thread's own processor clock is not /// supported everywhere; where it is not, this quietly measures nothing. pub fn start(self: *CpuTimer, io: Io) void { self.since = Io.Timestamp.now(io, .cpu_thread); } /// End it, adding the interval to the total. pub fn stop(self: *CpuTimer, io: Io) void { const began = self.since orelse return; self.since = null; const ended = Io.Timestamp.now(io, .cpu_thread); const elapsed = ended.nanoseconds - began.nanoseconds; if (elapsed > 0) self.total_ns += elapsed; } pub fn milliseconds(self: CpuTimer) u64 { return @intCast(@divTrunc(self.total_ns, std.time.ns_per_ms)); } }; /// The several windows the counters are reported over at once. /// /// The subsystems count cumulatively — a demodulator does not know or care /// about minutes — so what arrives here is a running total, and the /// difference from the last one is what goes into the windows. Everything /// else is bookkeeping: a fifteen-slot ring of completed minutes, from which /// the five- and fifteen-minute windows are recomputed whenever a minute /// rolls over. pub const Windows = struct { /// The last cumulative total seen, so the next one can be differenced /// against it. previous: Stats = .empty, /// The minute in progress. current: Stats = .empty, /// Since the process started. alltime: Stats = .empty, /// Since `--stats-every` last printed. periodic: Stats = .empty, /// Since the last completed minute. latest: Stats = .empty, /// The last fifteen completed minutes. one_minute: [15]Stats = @splat(.empty), /// Which slot holds the most recent. newest: usize = 0, five_minute: Stats = .empty, fifteen_minute: Stats = .empty, /// When the current minute ends. next_minute_ms: u64 = 0, /// Take a new cumulative total and fold the difference into every /// window. pub fn update(self: *Windows, cumulative: Stats, now: u64) void { var delta = cumulative; delta.subtract(self.previous); self.previous = cumulative; delta.start = self.current.start; delta.end = now; self.current.add(delta); self.current.end = now; // Settings rather than counts: carry the latest through. self.current.sdr_gain = cumulative.sdr_gain; self.current.adaptive_valid = cumulative.adaptive_valid; self.current.adaptive_range_gain_limit = cumulative.adaptive_range_gain_limit; self.current.adaptive_noise_dbfs = cumulative.adaptive_noise_dbfs; if (self.current.start == 0) self.current.start = now; } /// Fold the minute in progress into the longer windows and start a new /// one. Call once a second; it decides for itself whether a minute has /// passed. pub fn rollMinute(self: *Windows, now: u64) bool { if (self.next_minute_ms == 0) { self.next_minute_ms = now + 60_000; return false; } if (now < self.next_minute_ms) return false; self.next_minute_ms = now + 60_000; self.flush(); self.newest = (self.newest + 1) % self.one_minute.len; self.one_minute[self.newest] = self.latest; self.latest = .empty; self.five_minute = .empty; for (0..5) |i| { self.five_minute.add(self.one_minute[(self.newest + self.one_minute.len - i) % self.one_minute.len]); } self.fifteen_minute = .empty; for (0..15) |i| { self.fifteen_minute.add(self.one_minute[(self.newest + self.one_minute.len - i) % self.one_minute.len]); } return true; } /// Move what has accumulated in `current` into the longer windows, /// leaving `current` empty. Called before anything reads them. pub fn flush(self: *Windows) void { self.alltime.add(self.current); self.periodic.add(self.current); self.latest.add(self.current); const start = self.current.end; self.current = .empty; self.current.start = start; self.current.end = start; } /// Everything since the process started, up to date. pub fn total(self: *Windows) Stats { self.flush(); return self.alltime; } /// Everything since `--stats-every` last printed, and reset it. pub fn takePeriodic(self: *Windows) Stats { self.flush(); const result = self.periodic; self.periodic = .empty; return result; } }; /// What the report should include, which depends on how the receiver is /// configured. pub const Options = struct { /// Whether there is a radio at all. local: bool = true, /// Whether anything is coming in over the network. net: bool = false, /// How many levels of error correction to list. fix_bits: crc.FixBits = .none, /// Whether to draw the range histogram. range_histogram: bool = false, /// The furthest an aircraft can be, which scales the histogram. max_range: f64 = 1852 * 300, /// The gain in decibels at each step the source offers, which is what /// the gain figures are reported in. Empty if it has no gain control. gain_db: []const f64 = &.{}, }; /// The gain at a step, in decibels, clamped to the steps that exist. /// /// The adaptive controller reports a limit of −1 when it has decided every /// step is too loud, and the bottom step is the honest thing to show for it. pub fn gainDbAt(options: Options, step: i32) f64 { if (options.gain_db.len == 0) return 0; const index = std.math.clamp(step, 0, @as(i32, @intCast(options.gain_db.len - 1))); return options.gain_db[@intCast(index)]; } /// Write the report `--stats` prints. pub fn writeText(w: *Io.Writer, st: Stats, options: Options, zone: ?datetime.TimeZone) Io.Writer.Error!void { try w.writeAll("\n\n"); try w.writeAll("Statistics: "); try writeTimestamp(w, zone, st.start); try w.writeAll(" - "); try writeTimestamp(w, zone, st.end); try w.writeAll("\n"); if (options.local) try writeLocal(w, st, options); if (st.adaptive_valid) try writeAdaptive(w, st, options); if (options.net) try writeRemote(w, st, options); try writeDecoder(w, st); try writeCpu(w, st); if (options.range_histogram) try writeRangeHistogram(w, st, options.max_range); } fn writeLocal(w: *Io.Writer, st: Stats, options: Options) Io.Writer.Error!void { try w.writeAll("Local receiver:\n"); try w.print(" {d:>12} samples processed\n", .{st.samples_processed}); try w.print(" {d:>12} samples dropped\n", .{st.samples_dropped}); try w.print(" {d:>12} Mode A/C messages received\n", .{st.demod_modeac}); try w.print(" {d:>12} Mode-S message preambles received\n", .{st.demod_preambles}); try w.print(" {d:>12} with bad message format or invalid CRC\n", .{st.demod_rejected_bad}); try w.print(" {d:>12} with unrecognized ICAO address\n", .{st.demod_rejected_unknown_icao}); try w.print(" {d:>12} accepted with correct CRC\n", .{st.demod_accepted[0]}); for (1..correctionLevels(options.fix_bits) + 1) |level| { try w.print(" {d:>12} accepted with {d}-bit error repaired\n", .{ st.demod_accepted[level], level }); } try writeLevel(w, st.noiseDbfs(), "noise power"); try writeLevel(w, st.signalDbfs(), "mean signal power"); try writeLevel(w, st.peakDbfs(), "peak signal power"); try w.print(" {d:>5} messages with signal power above -3dBFS\n", .{st.strong_signal_count}); if (st.sdr_gain) |step| { try w.writeAll(" "); try writeAligned(w, 4, 1, gainDbAt(options, step)); try w.writeAll("dB current SDR gain\n"); } } /// What the adaptive gain controller has been doing, which is only printed /// once it has had a whole block to measure. fn writeAdaptive(w: *Io.Writer, st: Stats, options: Options) Io.Writer.Error!void { try w.writeAll("Adaptive gain:\n"); try w.print(" {d:>5} loud undecoded bursts\n", .{st.adaptive_loud_undecoded}); try w.print(" {d:>5} loud decoded messages\n", .{st.adaptive_loud_decoded}); try w.writeAll(" "); try writeAligned(w, 5, 1, st.adaptive_noise_dbfs); try w.writeAll(" dBFS latest noise floor\n"); try w.writeAll(" "); try writeAligned(w, 5, 1, gainDbAt(options, st.adaptive_range_gain_limit orelse 0)); try w.writeAll(" dB latest dynamic range gain upper limit\n"); try w.print(" {d:>5} gain changes caused by adaptive gain control\n", .{st.adaptive_gain_changes}); var total: u64 = 0; for (st.adaptive_gain_seconds) |seconds| total += seconds; if (total == 0) return; // The median gain step, which is the one the histogram's midpoint falls in. var running: u64 = 0; for (st.adaptive_gain_seconds, 0..) |seconds, step| { running += seconds; if (running >= total / 2) { try w.writeAll(" "); try writeAligned(w, 5, 1, gainDbAt(options, @intCast(step))); try w.writeAll(" dB median gain\n"); break; } } try w.writeAll(" Gain histogram:\n"); for (st.adaptive_gain_seconds, 0..) |seconds, step| { if (seconds == 0) continue; try w.writeAll(" "); try writeAligned(w, 5, 1, gainDbAt(options, @intCast(step))); try w.writeAll(" dB: "); try w.print("{d:>5} seconds (", .{seconds}); try writeAligned(w, 5, 1, 100.0 * @as(f64, @floatFromInt(seconds)) / @as(f64, @floatFromInt(total))); try w.writeAll("%)\n"); } } /// A power level in decibels, or a row of dashes where there was nothing to /// measure. fn writeLevel(w: *Io.Writer, value: ?f64, label: []const u8) Io.Writer.Error!void { if (value) |dbfs| { try w.writeAll(" "); try writeAligned(w, 5, 1, dbfs); try w.print(" dBFS {s}\n", .{label}); } else { try w.print(" ----- dBFS {s}\n", .{label}); } } fn writeRemote(w: *Io.Writer, st: Stats, options: Options) Io.Writer.Error!void { try w.writeAll("Messages from network clients:\n"); try w.print(" {d:>8} Mode A/C messages received\n", .{st.remote_received_modeac}); try w.print(" {d:>8} Mode S messages received\n", .{st.remote_received_modes}); try w.print(" {d:>8} with bad message format or invalid CRC\n", .{st.remote_rejected_bad}); try w.print(" {d:>8} with unrecognized ICAO address\n", .{st.remote_rejected_unknown_icao}); try w.print(" {d:>8} accepted with correct CRC\n", .{st.remote_accepted[0]}); for (1..correctionLevels(options.fix_bits) + 1) |level| { try w.print(" {d:>8} accepted with {d}-bit error repaired\n", .{ st.remote_accepted[level], level }); } } fn writeDecoder(w: *Io.Writer, st: Stats) Io.Writer.Error!void { try w.writeAll("Decoder:\n"); try w.print(" {d:>8} total usable messages\n", .{st.messages_total}); for (st.messages_by_df, 0..) |count, df| { if (count != 0) try w.print(" {d:>8} DF{d} messages\n", .{ count, df }); } try w.print(" {d:>8} surface position messages received\n", .{st.cpr_surface}); try w.print(" {d:>8} airborne position messages received\n", .{st.cpr_airborne}); try w.print(" {d:>8} global CPR attempts with valid positions\n", .{st.cpr_global_ok}); try w.print(" {d:>8} global CPR attempts with bad data\n", .{st.cpr_global_bad}); try w.print(" {d:>8} global CPR attempts that failed the range check\n", .{st.cpr_global_range_checks}); try w.print(" {d:>8} global CPR attempts that failed the speed check\n", .{st.cpr_global_speed_checks}); try w.print(" {d:>8} global CPR attempts with insufficient data\n", .{st.cpr_global_skipped}); try w.print(" {d:>8} local CPR attempts with valid positions\n", .{st.cpr_local_ok}); try w.print(" {d:>8} aircraft-relative positions\n", .{st.cpr_local_aircraft_relative}); try w.print(" {d:>8} receiver-relative positions\n", .{st.cpr_local_receiver_relative}); try w.print(" {d:>8} local CPR attempts that did not produce useful positions\n", .{st.cpr_local_skipped}); try w.print(" {d:>8} local CPR attempts that failed the range check\n", .{st.cpr_local_range_checks}); try w.print(" {d:>8} local CPR attempts that failed the speed check\n", .{st.cpr_local_speed_checks}); try w.print(" {d:>8} CPR messages that look like transponder failures filtered\n", .{st.cpr_filtered}); try w.print(" {d:>8} non-ES altitude messages from ES-equipped aircraft ignored\n", .{st.suppressed_altitude_messages}); try w.print(" {d:>8} unique aircraft tracks\n", .{st.unique_aircraft}); try w.print(" {d:>8} aircraft tracks where only one message was seen\n", .{st.single_message_aircraft}); try w.print(" {d:>8} aircraft tracks which were not marked reliable\n", .{st.unreliable_aircraft}); } fn writeCpu(w: *Io.Writer, st: Stats) Io.Writer.Error!void { const total = st.demod_cpu_ms + st.reader_cpu_ms + st.background_cpu_ms; const elapsed: f64 = @floatFromInt(st.end -| st.start + 1); try w.writeAll("CPU load: "); try writeAligned(w, 5, 1, 100.0 * @as(f64, @floatFromInt(total)) / elapsed); try w.writeAll("%\n"); try w.print(" {d:>5} ms for demodulation\n", .{st.demod_cpu_ms}); try w.print(" {d:>5} ms for reading from USB\n", .{st.reader_cpu_ms}); try w.print(" {d:>5} ms for network input and background tasks\n", .{st.background_cpu_ms}); } /// Draw the range histogram as a bar chart. /// /// Twenty rows of eighth-height block characters, so that a bar's height is /// readable to within an eighth of a row. The point of it is the *shape*: a /// receiver with a good antenna and a clear horizon has a smooth curve, and /// anything else — an obstruction, a bad connector — shows as a notch. fn writeRangeHistogram(w: *Io.Writer, st: Stats, max_range: f64) Io.Writer.Error!void { // Eight bar heights. The first is never used: a bar shorter than one // eighth prints as a space and anything at least one eighth indexes from // one, so the smallest visible bar is the second. That is upstream's // indexing, and changing it would change every histogram ever compared // against one. const pixels = [_][]const u8{ "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" }; const rows = 20; try w.writeAll("Range histogram:\n\n"); var peak: u64 = 0; for (st.range_histogram) |count| peak = @max(peak, count); if (peak == 0) peak = 1; var heights: [range_bucket_count]i32 = undefined; for (&heights, st.range_histogram) |*height, count| { height.* = @intFromFloat(@as(f64, @floatFromInt(count)) * rows * pixels.len / @as(f64, @floatFromInt(peak))); // A bucket with anything in it gets at least a sliver, so that a // faint but real lobe is visible. if (count > 0 and height.* == 0) height.* = 1; } for (0..rows) |row| { for (heights) |height| { const above = height - @as(i32, @intCast((rows - 1 - row) * pixels.len)); if (above <= 0) { try w.writeAll(" "); } else if (above >= pixels.len) { try w.writeAll(pixels[pixels.len - 1]); } else { try w.writeAll(pixels[@intCast(above)]); } } try w.writeAll("\n"); } for (0..range_bucket_count / 4) |_| try w.writeAll("----"); try w.writeAll("\n"); for (0..range_bucket_count / 4) |_| try w.writeAll(" ' "); try w.writeAll("\n"); for (0..range_bucket_count / 4) |i| { const midpoint = @round((@as(f64, @floatFromInt(i)) * 4 + 1.5) * max_range / range_bucket_count / 1000); try w.print("{d:0>3} ", .{@as(u32, @intFromFloat(@max(midpoint, 0)))}); } try w.writeAll("km\n"); } /// How many levels of correction there are to report. fn correctionLevels(fix_bits: crc.FixBits) usize { return switch (fix_bits) { .none => 0, .one => 1, .two => 2, }; } /// A float right-aligned in a field, as C's `%5.1f` is. fn writeAligned(w: *Io.Writer, width: usize, comptime decimals: comptime_int, value: f64) Io.Writer.Error!void { var buf: [64]u8 = undefined; var text: Io.Writer = .fixed(&buf); try fmt.fixed(&text, decimals, value); const rendered = text.buffered(); for (rendered.len..width) |_| try w.writeByte(' '); try w.writeAll(rendered); } /// A time as C's `%c %Z` renders it in the C locale, which is what upstream /// runs in: it never calls `setlocale`. /// /// Public because it is not only the statistics report that stamps a line /// this way: so does every line the program logs about its own lifetime. pub fn writeTimestamp(w: *Io.Writer, zone: ?datetime.TimeZone, millis: u64) Io.Writer.Error!void { const seconds: i64 = @intCast(millis / 1000); const local = if (zone) |z| z.atTimestamp(seconds) else datetime.Instant.fromMilliTimestamp(@intCast(millis)).asDateTime(); const weekdays = [_][]const u8{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; const months = [_][]const u8{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; try w.print("{s} {s} {d:>2} {d:0>2}:{d:0>2}:{d:0>2} {d}", .{ weekdays[@intFromEnum(local.weekday) % 7], months[@intFromEnum(local.month) - 1], local.day, local.hour, local.minute, local.second, @as(u32, @intCast(@max(local.year, 0))), }); // The zone's own abbreviation for this instant — "CDT" rather than // "America/Chicago" — which the reading carries with it. const designation = local.designation.slice(); if (designation.len > 0) try w.print(" {s}", .{designation}); } const testing = std.testing; test "a cumulative total becomes a per-window delta" { var windows: Windows = .{}; var cumulative: Stats = .empty; cumulative.messages_total = 100; windows.update(cumulative, 1000); cumulative.messages_total = 250; windows.update(cumulative, 2000); try testing.expectEqual(@as(u64, 250), windows.total().messages_total); try testing.expectEqual(@as(u64, 250), windows.alltime.messages_total); } test "a counter that goes backwards produces zero, not an enormous number" { var a: Stats = .empty; a.messages_total = 5; var b: Stats = .empty; b.messages_total = 10; a.subtract(b); try testing.expectEqual(@as(u64, 0), a.messages_total); } test "minutes roll into the longer windows" { var windows: Windows = .{}; // The first call only starts the clock. try testing.expect(!windows.rollMinute(0)); var cumulative: Stats = .empty; var minute: u64 = 0; while (minute < 20) : (minute += 1) { cumulative.messages_total += 10; const now = (minute + 1) * 60_000; windows.update(cumulative, now); try testing.expect(windows.rollMinute(now)); } // Twenty minutes of ten messages each. try testing.expectEqual(@as(u64, 200), windows.total().messages_total); try testing.expectEqual(@as(u64, 50), windows.five_minute.messages_total); try testing.expectEqual(@as(u64, 150), windows.fifteen_minute.messages_total); } test "the periodic window empties when it is taken" { var windows: Windows = .{}; var cumulative: Stats = .empty; cumulative.messages_total = 30; windows.update(cumulative, 1000); try testing.expectEqual(@as(u64, 30), windows.takePeriodic().messages_total); try testing.expectEqual(@as(u64, 0), windows.takePeriodic().messages_total); // But the running total is unaffected. cumulative.messages_total = 45; windows.update(cumulative, 2000); try testing.expectEqual(@as(u64, 45), windows.total().messages_total); } test "adding two windows sums their counters" { var a: Stats = .empty; a.start = 1000; a.end = 2000; a.messages_total = 10; a.demod_accepted = .{ 5, 3, 1 }; a.peak_signal_power = 0.5; a.range_histogram[3] = 7; var b: Stats = .empty; b.start = 2000; b.end = 3000; b.messages_total = 20; b.demod_accepted = .{ 1, 1, 1 }; b.peak_signal_power = 0.25; b.range_histogram[3] = 3; b.range_histogram[9] = 1; a.add(b); // The window spans both. try testing.expectEqual(@as(u64, 1000), a.start); try testing.expectEqual(@as(u64, 3000), a.end); // Counters sum, including arrays. try testing.expectEqual(@as(u64, 30), a.messages_total); try testing.expectEqualSlices(u64, &.{ 6, 4, 2 }, &a.demod_accepted); try testing.expectEqual(@as(u64, 10), a.range_histogram[3]); try testing.expectEqual(@as(u64, 1), a.range_histogram[9]); // The peak is the higher of the two, not their sum. try testing.expectEqual(@as(f64, 0.5), a.peak_signal_power); } test "adding to an empty window keeps the other's start" { var a: Stats = .empty; var b: Stats = .empty; b.start = 5000; b.end = 6000; a.add(b); try testing.expectEqual(@as(u64, 5000), a.start); try testing.expectEqual(@as(u64, 6000), a.end); } test "signal levels are decibels, or nothing at all" { var st: Stats = .empty; try testing.expectEqual(@as(?f64, null), st.noiseDbfs()); try testing.expectEqual(@as(?f64, null), st.signalDbfs()); try testing.expectEqual(@as(?f64, null), st.peakDbfs()); st.signal_power_sum = 1.0; st.signal_power_count = 10; // A tenth of full scale is -10 dBFS. try testing.expectApproxEqAbs(@as(f64, -10), st.signalDbfs().?, 1e-9); st.peak_signal_power = 1.0; try testing.expectApproxEqAbs(@as(f64, 0), st.peakDbfs().?, 1e-9); } test "the report says what was measured and what was not" { var st: Stats = .empty; st.start = 1_788_805_845_000; st.end = 1_788_805_905_000; st.demod_preambles = 1000; st.demod_accepted = .{ 800, 20, 0 }; st.messages_total = 820; st.messages_by_df[17] = 700; st.unique_aircraft = 42; var buf: [8192]u8 = undefined; var w: Io.Writer = .fixed(&buf); try writeText(&w, st, .{ .fix_bits = .one }, null); const text = w.buffered(); try testing.expect(std.mem.indexOf(u8, text, " 1000 Mode-S message preambles received\n") != null); try testing.expect(std.mem.indexOf(u8, text, " 800 accepted with correct CRC\n") != null); try testing.expect(std.mem.indexOf(u8, text, " 20 accepted with 1-bit error repaired\n") != null); // Two-bit correction was not enabled, so it is not reported. try testing.expect(std.mem.indexOf(u8, text, "2-bit error repaired") == null); // Nothing measured the noise, and the report says so rather than // claiming zero. try testing.expect(std.mem.indexOf(u8, text, " ----- dBFS noise power\n") != null); try testing.expect(std.mem.indexOf(u8, text, " 700 DF17 messages\n") != null); try testing.expect(std.mem.indexOf(u8, text, " 42 unique aircraft tracks\n") != null); // Downlink formats nothing arrived in are left out. try testing.expect(std.mem.indexOf(u8, text, "DF3 messages") == null); } test "the network section appears only when there is a network" { var st: Stats = .empty; st.remote_received_modes = 5; var buf: [8192]u8 = undefined; var without: Io.Writer = .fixed(&buf); try writeText(&without, st, .{}, null); try testing.expect(std.mem.indexOf(u8, without.buffered(), "Messages from network clients") == null); var with: Io.Writer = .fixed(&buf); try writeText(&with, st, .{ .net = true }, null); try testing.expect(std.mem.indexOf(u8, with.buffered(), " 5 Mode S messages received") != null); } test "the range histogram draws its bars" { var st: Stats = .empty; st.range_histogram[0] = 100; st.range_histogram[1] = 50; st.range_histogram[75] = 1; var buf: [16384]u8 = undefined; var w: Io.Writer = .fixed(&buf); try writeText(&w, st, .{ .range_histogram = true, .max_range = 1852 * 300 }, null); const text = w.buffered(); try testing.expect(std.mem.indexOf(u8, text, "Range histogram:") != null); // The tallest bucket reaches the top row. try testing.expect(std.mem.indexOf(u8, text, "█") != null); // A bucket with a single reception still shows, as the smallest bar the // indexing can produce. try testing.expect(std.mem.indexOf(u8, text, "▂") != null); try testing.expect(std.mem.indexOf(u8, text, "▁") == null); // And the scale runs to the configured maximum range. try testing.expect(std.mem.endsWith(u8, text, "km\n")); }