// 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 //! Reading frames somebody else received. //! //! A receiver is often not the only one: messages arrive over the network //! from a Beast device on a serial-to-TCP bridge, from another copy of this //! program, or from a multilateration server sending back positions it //! computed. The formats are the same ones the outputs write, read the other //! way about. //! //! Both parsers are deliberately unforgiving and deliberately silent. A //! connection can be joined part way through a frame, and a byte stream //! offers no way to tell that from a corrupt one — so anything that does not //! parse is dropped and the parser resynchronises, rather than closing the //! connection on what may be nothing worse than a late arrival. const std = @import("std"); const message = @import("message.zig"); const modes = @import("modes.zig"); const output = @import("output.zig"); /// A frame taken off the wire, with whatever the sender knew about it. pub const Frame = struct { /// The frame bytes. data: [modes.max_message_bytes]u8, /// How many of them are meaningful. len: u8, /// The sender's receive clock, in twelfths of a microsecond. timestamp: u64, /// The signal power as a fraction of full scale, or zero if the sender /// did not say. signal_level: f64, pub fn bytes(self: *const Frame) []const u8 { return self.data[0..self.len]; } /// Whether this is a Mode A/C reply rather than a Mode S frame. pub fn isModeAc(self: *const Frame) bool { return self.len == 2; } /// The Mode A/C code, for a two-byte frame. pub fn modeAcCode(self: *const Frame) u16 { return (@as(u16, self.data[0]) << 8) | self.data[1]; } }; /// Turn a signal level byte into the power fraction the decoder wants. /// /// The byte is an amplitude, so squaring it gives power. Both input formats /// encode it the same way. fn signalFromByte(byte: u8) f64 { const amplitude = @as(f64, @floatFromInt(byte)) / 255.0; return amplitude * amplitude; } /// The Beast binary format. pub const beast = struct { /// What one call to `parse` found. pub const Parsed = struct { /// How many bytes to drop from the front of the buffer. Zero means /// nothing could be decided yet. consumed: usize, /// The frame, if one was there. frame: ?Frame = null, /// A Radarcape receiver announcing where it is. position: ?Position = null, }; /// Where a Radarcape says it is, from a type 5 frame. pub const Position = struct { latitude: f32, longitude: f32, altitude: f32, }; /// How many payload bytes follow the header, for each frame type. fn payloadLength(kind: u8) ?usize { return switch (kind) { '1' => 2, // Mode A/C '2' => modes.MessageLength.short.bytes(), '3' => modes.MessageLength.long.bytes(), // Type 4 is a status word and type 5 a receiver position; both // are framed as though they were long messages. '4', '5' => modes.MessageLength.long.bytes(), else => null, }; } /// Take the next frame from the front of `buffer`. /// /// Anything before the first escape byte is junk — the tail of a frame a /// connection was joined in the middle of — and is consumed silently. /// A `consumed` of zero means the buffer does not yet hold enough to /// decide anything; wait for more and call again. pub fn parse(buffer: []const u8, mode_ac_enabled: bool) Parsed { const start = std.mem.indexOfScalar(u8, buffer, output.beast.escape) orelse // No escape byte at all: everything here is junk. return .{ .consumed = buffer.len }; // Not enough to know what follows the escape. if (start + 1 >= buffer.len) return .{ .consumed = start }; const kind = buffer[start + 1]; const payload_len = payloadLength(kind) orelse // Not a frame type; step over the escape and look again. return .{ .consumed = start + 2 }; // Six timestamp bytes and one signal byte, then the payload. Any // escape byte among them is doubled, so the frame is longer on the // wire than it is in meaning. const wanted = 6 + 1 + payload_len; var unescaped: [6 + 1 + modes.max_message_bytes]u8 = undefined; var read: usize = 0; var cursor = start + 2; while (read < wanted) { if (cursor >= buffer.len) return .{ .consumed = 0 }; // wait for more const byte = buffer[cursor]; cursor += 1; if (byte == output.beast.escape) { // A doubled escape byte is one byte of payload; a lone one is // the start of the next frame, and this one was truncated. if (cursor >= buffer.len) return .{ .consumed = 0 }; if (buffer[cursor] != output.beast.escape) return .{ .consumed = start + 1 }; cursor += 1; } unescaped[read] = byte; read += 1; } const consumed = cursor; if (kind == '5') { // A Radarcape position, which uses the whole frame for three // little-endian floats rather than for a message. return .{ .consumed = consumed, .position = .{ .latitude = floatFromBytes(unescaped[4..8]), .longitude = floatFromBytes(unescaped[8..12]), .altitude = floatFromBytes(unescaped[12..16]), }, }; } // Type 4 is a status word this does not read. if (kind == '4') return .{ .consumed = consumed }; if (kind == '1' and !mode_ac_enabled) return .{ .consumed = consumed }; var frame: Frame = .{ .data = @splat(0), .len = @intCast(payload_len), .timestamp = 0, .signal_level = signalFromByte(unescaped[6]), }; for (unescaped[0..6]) |byte| frame.timestamp = (frame.timestamp << 8) | byte; @memcpy(frame.data[0..payload_len], unescaped[7..][0..payload_len]); return .{ .consumed = consumed, .frame = frame }; } fn floatFromBytes(bytes: *const [4]u8) f32 { return @bitCast(std.mem.readInt(u32, bytes, .little)); } }; /// The AVR text formats, in all the variants that have accumulated. pub const avr = struct { /// Parse one line, without its terminator. /// /// Five prefixes are accepted, which differ in what the sender knew: /// /// * `*` and `:` — just the frame. /// * `@` and `%` — a timestamp first. `%` also claims the CRC checked /// out, which is not taken on trust: the frame is checked again here. /// * `<` — a timestamp and a signal level, which is what a Beast in text /// mode sends. pub fn parse(line: []const u8, mode_ac_enabled: bool) ?Frame { var text = std.mem.trim(u8, line, " \t\r\n"); if (text.len == 0 or text[text.len - 1] != ';') return null; var timestamp: u64 = 0; var signal_level: f64 = 0; switch (text[0]) { '<' => { // '<', twelve timestamp digits, two signal digits, the frame, // then the semicolon. if (text.len < 18) return null; timestamp = hexValue(u64, text[1..13]) orelse return null; signal_level = signalFromByte(hexValue(u8, text[13..15]) orelse return null); text = text[15 .. text.len - 1]; }, '@', '%' => { if (text.len < 16) return null; timestamp = hexValue(u64, text[1..13]) orelse return null; text = text[13 .. text.len - 1]; }, '*', ':' => { if (text.len < 4) return null; text = text[1 .. text.len - 1]; }, else => return null, } // Two hex digits per byte, and only the three real frame lengths. if (text.len % 2 != 0) return null; const len = text.len / 2; switch (len) { 2 => if (!mode_ac_enabled) return null, 7, 14 => {}, else => return null, } var frame: Frame = .{ .data = @splat(0), .len = @intCast(len), .timestamp = timestamp, .signal_level = signal_level, }; for (0..len) |i| { frame.data[i] = hexValue(u8, text[i * 2 ..][0..2]) orelse return null; } return frame; } /// Read hex digits as an integer, or null if any of them is not a hex /// digit. fn hexValue(comptime T: type, digits: []const u8) ?T { var value: T = 0; for (digits) |digit| { const nibble: T = switch (digit) { '0'...'9' => @intCast(digit - '0'), 'a'...'f' => @intCast(digit - 'a' + 10), 'A'...'F' => @intCast(digit - 'A' + 10), else => return null, }; value = (value << 4) | nibble; } return value; } }; const testing = std.testing; const df17 = [_]u8{ 0x8d, 0x48, 0x40, 0xd6, 0x20, 0x2c, 0xc3, 0x71, 0xc3, 0x2c, 0xe0, 0x57, 0x60, 0x98 }; test "a Beast frame round-trips through the output writer" { var buf: [128]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try output.beast.write(&w, 0x0123456789ab, 0.25, &df17); const parsed = beast.parse(w.buffered(), false); try testing.expectEqual(w.buffered().len, parsed.consumed); const frame = parsed.frame.?; try testing.expectEqualSlices(u8, &df17, frame.bytes()); try testing.expectEqual(@as(u64, 0x0123456789ab), frame.timestamp); // The level is quantised to a byte on the way out, so it comes back // close rather than exact. try testing.expectApproxEqAbs(@as(f64, 0.25), frame.signal_level, 0.01); } test "Beast escape bytes are undoubled" { var buf: [128]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); const frame = [_]u8{ 0x1a, 0x00, 0x1a, 0x1a, 0x00, 0x00, 0x1a }; try output.beast.write(&w, 0x1a00000000ab, 0, &frame); const parsed = beast.parse(w.buffered(), false); try testing.expectEqual(w.buffered().len, parsed.consumed); try testing.expectEqualSlices(u8, &frame, parsed.frame.?.bytes()); try testing.expectEqual(@as(u64, 0x1a00000000ab), parsed.frame.?.timestamp); } test "junk before a frame is thrown away" { var buf: [128]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try w.writeAll("the tail of a frame we joined half way through"); try output.beast.write(&w, 1000, 0.5, &df17); var remaining = w.buffered(); var found: ?Frame = null; while (remaining.len > 0) { const parsed = beast.parse(remaining, false); if (parsed.consumed == 0) break; remaining = remaining[parsed.consumed..]; if (parsed.frame) |frame| found = frame; } try testing.expectEqualSlices(u8, &df17, found.?.bytes()); } test "an incomplete Beast frame waits for more" { var buf: [128]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try output.beast.write(&w, 1000, 0.5, &df17); const whole = w.buffered(); // Every prefix short of the whole frame should ask for more rather than // producing something. for (1..whole.len) |n| { const parsed = beast.parse(whole[0..n], false); try testing.expectEqual(@as(?Frame, null), parsed.frame); try testing.expectEqual(@as(usize, 0), parsed.consumed); } } test "Mode A/C frames arrive only when they are wanted" { // Escape, type, six timestamp bytes, a signal level, and two of payload. const frame = [_]u8{ output.beast.escape, '1', 0, 0, 0, 0, 0, 1, 0x80, 0x77, 0x00 }; const ignored = beast.parse(&frame, false); try testing.expectEqual(@as(?Frame, null), ignored.frame); try testing.expectEqual(frame.len, ignored.consumed); const accepted = beast.parse(&frame, true); try testing.expectEqual(@as(u8, 2), accepted.frame.?.len); try testing.expect(accepted.frame.?.isModeAc()); try testing.expectEqual(@as(u16, 0x7700), accepted.frame.?.modeAcCode()); } test "a Radarcape position frame" { var frame: [2 + 21]u8 = @splat(0); frame[0] = output.beast.escape; frame[1] = '5'; std.mem.writeInt(u32, frame[2 + 4 ..][0..4], @bitCast(@as(f32, 52.25)), .little); std.mem.writeInt(u32, frame[2 + 8 ..][0..4], @bitCast(@as(f32, 3.92)), .little); std.mem.writeInt(u32, frame[2 + 12 ..][0..4], @bitCast(@as(f32, 12.5)), .little); const parsed = beast.parse(&frame, false); try testing.expectEqual(@as(?Frame, null), parsed.frame); const position = parsed.position.?; try testing.expectApproxEqAbs(@as(f32, 52.25), position.latitude, 1e-6); try testing.expectApproxEqAbs(@as(f32, 3.92), position.longitude, 1e-6); try testing.expectApproxEqAbs(@as(f32, 12.5), position.altitude, 1e-6); } test "an unknown Beast frame type is stepped over" { const junk = [_]u8{ output.beast.escape, 'Z', 1, 2, 3 }; const parsed = beast.parse(&junk, false); try testing.expectEqual(@as(?Frame, null), parsed.frame); try testing.expectEqual(@as(usize, 2), parsed.consumed); } test "AVR text, in each of its prefixes" { const bare = avr.parse("*8D4840D6202CC371C32CE0576098;", false).?; try testing.expectEqualSlices(u8, &df17, bare.bytes()); try testing.expectEqual(@as(u64, 0), bare.timestamp); const colon = avr.parse(":8D4840D6202CC371C32CE0576098;", false).?; try testing.expectEqualSlices(u8, &df17, colon.bytes()); const timed = avr.parse("@0123456789AB8D4840D6202CC371C32CE0576098;", false).?; try testing.expectEqualSlices(u8, &df17, timed.bytes()); try testing.expectEqual(@as(u64, 0x0123456789ab), timed.timestamp); // '%' claims the CRC was checked; it is checked again here regardless, // so the only difference is the character. const checked = avr.parse("%0123456789AB8D4840D6202CC371C32CE0576098;", false).?; try testing.expectEqualSlices(u8, &df17, checked.bytes()); const with_signal = avr.parse("<0123456789ABFF8D4840D6202CC371C32CE0576098;", false).?; try testing.expectEqualSlices(u8, &df17, with_signal.bytes()); try testing.expectEqual(@as(u64, 0x0123456789ab), with_signal.timestamp); try testing.expectApproxEqAbs(@as(f64, 1.0), with_signal.signal_level, 1e-9); } test "AVR text is case-insensitive and tolerates surrounding space" { const lower = avr.parse(" *8d4840d6202cc371c32ce0576098; ", false).?; try testing.expectEqualSlices(u8, &df17, lower.bytes()); } test "malformed AVR lines are dropped rather than guessed at" { // No terminator. try testing.expectEqual(@as(?Frame, null), avr.parse("*8D4840D6202CC371C32CE0576098", false)); // Not a prefix we know. try testing.expectEqual(@as(?Frame, null), avr.parse("!8D4840D6202CC371C32CE0576098;", false)); // Not a hex digit. try testing.expectEqual(@as(?Frame, null), avr.parse("*8D4840D6202CC371C32CE05760ZZ;", false)); // Not a frame length. try testing.expectEqual(@as(?Frame, null), avr.parse("*8D4840D6;", false)); try testing.expectEqual(@as(?Frame, null), avr.parse("*8D4840D6202CC371C32CE057609801;", false)); // An odd number of digits. try testing.expectEqual(@as(?Frame, null), avr.parse("*8D4840D6202CC371C32CE05760980;", false)); // Truncated timestamps. try testing.expectEqual(@as(?Frame, null), avr.parse("@0123;", false)); try testing.expectEqual(@as(?Frame, null), avr.parse("<0123;", false)); // Empty. try testing.expectEqual(@as(?Frame, null), avr.parse("", false)); try testing.expectEqual(@as(?Frame, null), avr.parse(";", false)); } test "AVR Mode A/C frames arrive only when they are wanted" { try testing.expectEqual(@as(?Frame, null), avr.parse("*7700;", false)); const frame = avr.parse("*7700;", true).?; try testing.expect(frame.isModeAc()); try testing.expectEqual(@as(u16, 0x7700), frame.modeAcCode()); } test "a stream of Beast frames is parsed one after another" { var buf: [512]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); for (0..5) |i| { var frame = df17; frame[13] = @intCast(i); try output.beast.write(&w, 1000 + i, 0.5, &frame); } var remaining = w.buffered(); var count: usize = 0; while (remaining.len > 0) { const parsed = beast.parse(remaining, false); if (parsed.consumed == 0) break; remaining = remaining[parsed.consumed..]; if (parsed.frame) |frame| { try testing.expectEqual(@as(u8, @intCast(count)), frame.data[13]); try testing.expectEqual(@as(u64, 1000 + count), frame.timestamp); count += 1; } } try testing.expectEqual(@as(usize, 5), count); }