From 8f87263c78f220d6b12bb125b288dac4e3978feb Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Sat, 14 Nov 2026 23:38:03 +0100 Subject: [PATCH 01/13] feat(cli): --format csv, stdin streams via '-', and telecommand inspection Telemetry decoding often feeds analysis pipelines, spreadsheets, and stream processors, where plain text table and JSON lines require extra parsing or do not stream into CSV consumers cleanly. xtce was also strictly file-bound, failing if piped input used the standard '-' convention. * `--format csv` outputs tabular parameter values per packet: `packet,container,parameter,eng` (and an optional `,raw` column with `--raw`). RFC 4180 escaping is applied when strings contain commas, double quotes, or newlines. * `--no-summary` suppresses the trailing timing and packet count lines, leaving stdout clean for piping directly into downstream tools (`xsv`, `jq`, Pandas). * Reading from standard input (`-`) is now supported across the CLI: `xtce decode` accepts `-` for either the packet stream or the definition, and `xtce info`, `xtce codegen` and `xtce bench` accept `-` for definition files. * `xtce info --verbose` now lists the telecommands section, showing each command, inheritance, backing container, and declared argument types. Tests added for CSV string escaping, float formatting, and tabular output. All 9 differential cases match the reference, fmt and clippy clean. --- Cargo.lock | 12 +- crates/xtce-cli/src/decode.rs | 301 +++++++++++++++++++++++++++++++--- crates/xtce-cli/src/info.rs | 48 +++++- crates/xtce-cli/src/main.rs | 193 +++++++++++++--------- 4 files changed, 445 insertions(+), 109 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 79a8b0e..e1dd06f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -915,7 +915,7 @@ checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" [[package]] name = "xtask" -version = "0.1.0" +version = "0.1.1" dependencies = [ "clap", "serde_json", @@ -925,7 +925,7 @@ dependencies = [ [[package]] name = "xtce-cli" -version = "0.1.0" +version = "0.1.1" dependencies = [ "clap", "xtce-codegen", @@ -935,7 +935,7 @@ dependencies = [ [[package]] name = "xtce-codegen" -version = "0.1.0" +version = "0.1.1" dependencies = [ "criterion", "prettyplease", @@ -949,7 +949,7 @@ dependencies = [ [[package]] name = "xtce-codegen-e2e" -version = "0.1.0" +version = "0.1.1" dependencies = [ "xtce-codegen", "xtce-decode", @@ -958,7 +958,7 @@ dependencies = [ [[package]] name = "xtce-decode" -version = "0.1.0" +version = "0.1.1" dependencies = [ "criterion", "proptest", @@ -968,7 +968,7 @@ dependencies = [ [[package]] name = "xtce-model" -version = "0.1.0" +version = "0.1.1" dependencies = [ "criterion", "proptest", diff --git a/crates/xtce-cli/src/decode.rs b/crates/xtce-cli/src/decode.rs index 18de97a..dde4556 100644 --- a/crates/xtce-cli/src/decode.rs +++ b/crates/xtce-cli/src/decode.rs @@ -1,6 +1,6 @@ //! `xtce decode` — run a packet stream through a definition and print the values. -use std::io::Write; +use std::io::{Read, Write}; use std::path::Path; use std::time::Instant; @@ -14,6 +14,8 @@ pub enum Format { Table, /// One JSON object per packet, one packet per line. Jsonl, + /// Comma-separated values (CSV) with packet, container, and parameter columns. + Csv, /// Nothing per packet; only the summary. Quiet, } @@ -28,6 +30,62 @@ pub struct Options<'a> { pub only: &'a [String], pub format: Format, pub show_raw: bool, + pub no_summary: bool, +} + +fn load_stream(packets: &Path) -> std::io::Result> { + if packets.as_os_str() == "-" { + let mut bytes = Vec::new(); + std::io::stdin().read_to_end(&mut bytes)?; + Ok(bytes) + } else { + std::fs::read(packets) + } +} + +fn load_definition(definition: &Path) -> Result> { + if definition.as_os_str() == "-" { + let mut xml = String::new(); + std::io::stdin().read_to_string(&mut xml)?; + Ok(XtceDb::from_xml(&xml)?) + } else { + Ok(XtceDb::from_path(definition)?) + } +} + +struct Summary { + total: usize, + decoded: usize, + unrecognised: usize, + failed: usize, + trailing: usize, + load_elapsed: std::time::Duration, + decode_elapsed: std::time::Duration, +} + +fn print_summary(out: &mut impl Write, summary: &Summary) -> std::io::Result<()> { + writeln!(out)?; + writeln!( + out, + "{} packet(s): {} decoded, {} not described, {} failed", + summary.total, summary.decoded, summary.unrecognised, summary.failed + )?; + if summary.trailing > 0 { + // Worth surfacing: the definition and the packets disagree about length, which + // usually means a container is missing entries rather than that anything is corrupt. + writeln!( + out, + "{} packet(s) had bits no entry claimed — the definition may be incomplete", + summary.trailing + )?; + } + writeln!( + out, + "load {:.2} ms, decode {:.2} ms ({:.1} packets/s)", + summary.load_elapsed.as_secs_f64() * 1e3, + summary.decode_elapsed.as_secs_f64() * 1e3, + summary.decoded as f64 / summary.decode_elapsed.as_secs_f64().max(f64::MIN_POSITIVE), + ) } /// Decodes a stream and writes the result. @@ -39,8 +97,12 @@ pub struct Options<'a> { /// not well-framed. A packet that fails to *decode* is reported and counted, not fatal: one /// malformed frame in a downlink should not end the run. pub fn run(options: &Options<'_>) -> Result<(), Box> { + if options.definition.as_os_str() == "-" && options.packets.as_os_str() == "-" { + return Err("cannot read both definition and packets from standard input".into()); + } + let load_start = Instant::now(); - let db = XtceDb::from_path(options.definition)?; + let db = load_definition(options.definition)?; let load_elapsed = load_start.elapsed(); check_only(&db, options.only)?; @@ -50,7 +112,7 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { None => Decoder::new(&db)?, }; - let stream = std::fs::read(options.packets)?; + let stream = load_stream(options.packets)?; let stdout = std::io::stdout(); let mut out = std::io::BufWriter::new(stdout.lock()); @@ -63,6 +125,14 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { // One packet buffer for the whole stream: after the first packet this allocates nothing. let mut packet = decoder.new_packet(&stream); + if options.format == Format::Csv { + if options.show_raw { + writeln!(out, "packet,container,parameter,eng,raw")?; + } else { + writeln!(out, "packet,container,parameter,eng")?; + } + } + let decode_start = Instant::now(); for (index, framed) in PacketIter::new(&stream, options.skip_header_bytes).enumerate() { if options.limit.is_some_and(|limit| total >= limit) { @@ -80,46 +150,49 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { match options.format { Format::Table => write_table(&mut out, index, &packet, options)?, Format::Jsonl => write_jsonl(&mut out, index, &packet, options)?, + Format::Csv => write_csv(&mut out, index, &packet, options)?, Format::Quiet => {} } } Err(DecodeError::UnrecognizedPacket { container, .. }) => { unrecognised += 1; - if options.format != Format::Quiet { + if options.format == Format::Table { writeln!( out, "packet {index}: not described by this definition (no inheritor of {container} matches)" )?; + } else if options.format != Format::Quiet { + eprintln!( + "packet {index}: not described by this definition (no inheritor of {container} matches)" + ); } } Err(error) => { failed += 1; - writeln!(out, "packet {index}: {error}")?; + if options.format == Format::Table { + writeln!(out, "packet {index}: {error}")?; + } else { + eprintln!("packet {index}: {error}"); + } } } } let decode_elapsed = decode_start.elapsed(); - writeln!(out)?; - writeln!( - out, - "{total} packet(s): {decoded_count} decoded, {unrecognised} not described, {failed} failed" - )?; - if trailing > 0 { - // Worth surfacing: the definition and the packets disagree about length, which - // usually means a container is missing entries rather than that anything is corrupt. - writeln!( - out, - "{trailing} packet(s) had bits no entry claimed — the definition may be incomplete" + if !options.no_summary { + print_summary( + &mut out, + &Summary { + total, + decoded: decoded_count, + unrecognised, + failed, + trailing, + load_elapsed, + decode_elapsed, + }, )?; } - writeln!( - out, - "load {:.2} ms, decode {:.2} ms ({:.1} packets/s)", - load_elapsed.as_secs_f64() * 1e3, - decode_elapsed.as_secs_f64() * 1e3, - decoded_count as f64 / decode_elapsed.as_secs_f64().max(f64::MIN_POSITIVE), - )?; out.flush()?; if failed > 0 { @@ -382,6 +455,94 @@ fn write_json_string(out: &mut impl Write, text: &str) -> std::io::Result<()> { Ok(()) } +fn write_csv( + out: &mut impl Write, + index: usize, + packet: &xtce_decode::DecodedPacket<'_, '_>, + options: &Options<'_>, +) -> std::io::Result<()> { + let db = packet.db(); + let container = db + .container(packet.container()) + .map_or("?", |container| db.name(container.name)); + for (name, value) in packet.iter_named() { + if !wanted(options.only, name) { + continue; + } + write!(out, "{index},")?; + write_csv_string(out, container)?; + write!(out, ",")?; + write_csv_string(out, name)?; + write!(out, ",")?; + write_csv_eng(out, &value.eng)?; + if options.show_raw { + write!(out, ",")?; + write_csv_raw(out, &value.raw)?; + } + writeln!(out)?; + } + Ok(()) +} + +fn write_csv_eng(out: &mut impl Write, value: &EngValue<'_, '_>) -> std::io::Result<()> { + match value { + EngValue::Unsigned(number) => write!(out, "{number}"), + EngValue::Signed(number) => write!(out, "{number}"), + EngValue::Float(number) => write_csv_float(out, *number), + EngValue::Bool(flag) => write!(out, "{flag}"), + EngValue::Label(text) => write_csv_string(out, text), + EngValue::Text(text) => write_csv_string(out, text.as_ref()), + EngValue::Bytes(bytes) => write_hex_raw(out, bytes), + } +} + +fn write_csv_raw(out: &mut impl Write, value: &RawValue<'_>) -> std::io::Result<()> { + match value { + RawValue::Unsigned(number) => write!(out, "{number}"), + RawValue::Signed(number) => write!(out, "{number}"), + RawValue::Float(number) => write_csv_float(out, *number), + RawValue::Bytes(bytes) => write_hex_raw(out, bytes), + } +} + +fn write_csv_float(out: &mut impl Write, value: f64) -> std::io::Result<()> { + if value.is_nan() { + write!(out, "NaN") + } else if value.is_infinite() { + if value.is_sign_positive() { + write!(out, "Infinity") + } else { + write!(out, "-Infinity") + } + } else { + write!(out, "{value}") + } +} + +fn write_hex_raw(out: &mut impl Write, bytes: &[u8]) -> std::io::Result<()> { + for byte in bytes { + write!(out, "{byte:02x}")?; + } + Ok(()) +} + +fn write_csv_string(out: &mut impl Write, text: &str) -> std::io::Result<()> { + if text.contains([',', '"', '\n', '\r']) { + out.write_all(b"\"")?; + for ch in text.chars() { + if ch == '"' { + out.write_all(b"\"\"")?; + } else { + let mut buf = [0u8; 4]; + out.write_all(ch.encode_utf8(&mut buf).as_bytes())?; + } + } + out.write_all(b"\"") + } else { + out.write_all(text.as_bytes()) + } +} + #[cfg(test)] mod tests { use super::{check_only, edit_distance, glob_matches, suggest, wanted}; @@ -568,4 +729,98 @@ mod tests { // Two characters apart is still two edits: only *adjacent* swaps are one. assert_eq!(edit_distance("ABCD", "CBAD"), 2); } + + #[test] + fn csv_string_escapes_only_when_needed() { + let mut out = Vec::new(); + super::write_csv_string(&mut out, "plain_identifier").unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "plain_identifier"); + + let mut out = Vec::new(); + super::write_csv_string(&mut out, "comma, separated").unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "\"comma, separated\""); + + let mut out = Vec::new(); + super::write_csv_string(&mut out, "contains \"quotes\" inside").unwrap(); + assert_eq!( + String::from_utf8(out).unwrap(), + "\"contains \"\"quotes\"\" inside\"" + ); + + let mut out = Vec::new(); + super::write_csv_string(&mut out, "line1\nline2").unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "\"line1\nline2\""); + } + + #[test] + fn csv_float_formats_special_values() { + let mut out = Vec::new(); + super::write_csv_float(&mut out, 42.5).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "42.5"); + + let mut out = Vec::new(); + super::write_csv_float(&mut out, f64::NAN).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "NaN"); + + let mut out = Vec::new(); + super::write_csv_float(&mut out, f64::INFINITY).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "Infinity"); + + let mut out = Vec::new(); + super::write_csv_float(&mut out, f64::NEG_INFINITY).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "-Infinity"); + } + + #[test] + fn csv_formatting_writes_headers_and_rows() { + let db = db(); + let decoder = xtce_decode::Decoder::new(&db).expect("decoder creates"); + let data = [0x00, 0x00, 0x00, 0x2A]; + let mut packet = decoder.new_packet(&data); + decoder.decode_into(&mut packet, &data).expect("decodes"); + + let mut out = Vec::new(); + let options = super::Options { + definition: std::path::Path::new("dummy.xml"), + packets: std::path::Path::new("dummy.bin"), + root: None, + skip_header_bytes: 0, + limit: None, + only: &[], + format: super::Format::Csv, + show_raw: false, + no_summary: false, + }; + + super::write_csv(&mut out, 0, &packet, &options).expect("writes csv"); + let text = String::from_utf8(out).expect("utf8"); + assert_eq!(text, "0,PKT,ADGPSPOSX,42\n"); + + let mut out = Vec::new(); + let options_raw = super::Options { + show_raw: true, + ..options + }; + super::write_csv(&mut out, 0, &packet, &options_raw).expect("writes csv raw"); + let text_raw = String::from_utf8(out).expect("utf8"); + assert_eq!(text_raw, "0,PKT,ADGPSPOSX,42,42\n"); + } + + #[test] + fn print_summary_writes_formatted_counts() { + let mut out = Vec::new(); + let summary = super::Summary { + total: 10, + decoded: 8, + unrecognised: 1, + failed: 1, + trailing: 2, + load_elapsed: std::time::Duration::from_millis(5), + decode_elapsed: std::time::Duration::from_millis(15), + }; + super::print_summary(&mut out, &summary).expect("prints summary"); + let text = String::from_utf8(out).expect("utf8"); + assert!(text.contains("10 packet(s): 8 decoded, 1 not described, 1 failed")); + assert!(text.contains("2 packet(s) had bits no entry claimed")); + } } diff --git a/crates/xtce-cli/src/info.rs b/crates/xtce-cli/src/info.rs index 6e5b62c..e9a49ef 100644 --- a/crates/xtce-cli/src/info.rs +++ b/crates/xtce-cli/src/info.rs @@ -9,7 +9,7 @@ pub fn report(db: &XtceDb, elapsed: Duration, verbose: bool) { let stats = db.stats(); let source = db .source() - .map_or_else(|| "".to_owned(), |path| path.display().to_string()); + .map_or_else(|| "".to_owned(), |path| path.display().to_string()); println!("{source}"); println!( @@ -97,6 +97,7 @@ pub fn report(db: &XtceDb, elapsed: Duration, verbose: bool) { if verbose { print_containers(db); + print_commands(db); } println!(); } @@ -263,3 +264,48 @@ fn print_containers(db: &XtceDb) { } } } + +fn print_commands(db: &XtceDb) { + if db.meta_commands().is_empty() { + return; + } + println!(" telecommands:"); + for command in db.meta_commands() { + let base = command + .base + .and_then(|base| db.meta_command(base)) + .map(|base| format!(" extends {}", db.name(base.name))) + .unwrap_or_default(); + let container = command + .container + .and_then(|c| db.container(c)) + .map(|c| format!(" -> {}", db.name(c.name))) + .unwrap_or_default(); + println!( + " {}{}{}{}", + db.name(command.name), + if command.is_abstract { + " (abstract)" + } else { + "" + }, + base, + container + ); + for ¶m_id in &command.arguments { + let Some(param) = db.parameter(param_id) else { + continue; + }; + let ty = db.type_of(param_id); + let bits = ty + .and_then(xtce_model::ParameterType::fixed_size_in_bits) + .map_or_else(|| "var".to_owned(), |bits| format!("{bits}b")); + println!( + " {:<28} {:<16} {}", + db.name(param.name), + ty.map_or("?", |ty| ty.kind.label()), + bits + ); + } + } +} diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index f1e5230..274d5ce 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -11,7 +11,8 @@ #![allow(clippy::doc_markdown)] #![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] -use std::path::PathBuf; +use std::io::Read; +use std::path::{Path, PathBuf}; use std::process::ExitCode; use std::time::Instant; @@ -32,7 +33,7 @@ struct Cli { enum Command { /// Summarise one or more XTCE files: space systems, counts, and anything not decodable. Info { - /// XTCE files to inspect. + /// XTCE files to inspect. Use '-' to read from standard input. #[arg(required = true)] files: Vec, @@ -43,10 +44,10 @@ enum Command { /// Decode a CCSDS packet stream against an XTCE definition. Decode { - /// XTCE definition. + /// XTCE definition. Use '-' to read from standard input. definition: PathBuf, - /// File of concatenated CCSDS packets. + /// File of concatenated CCSDS packets. Use '-' to read from standard input. packets: PathBuf, /// Container to start from. Defaults to CCSDSPacket, CCSDSTelemetryPacket, or the @@ -74,11 +75,15 @@ enum Command { /// Also show the raw value alongside the engineering value. #[arg(long)] raw: bool, + + /// Suppress the final summary (load and decode timing, packet counts). + #[arg(long)] + no_summary: bool, }, /// Compile a definition into a static Rust decoder. Codegen { - /// XTCE definition. + /// XTCE definition. Use '-' to read from standard input. definition: PathBuf, /// Container to start from. @@ -92,7 +97,7 @@ enum Command { /// Time loading an XTCE file. Bench { - /// XTCE file to load. + /// XTCE file to load. Use '-' to read from standard input. file: PathBuf, /// Number of load iterations to time. @@ -116,26 +121,19 @@ fn main() -> ExitCode { } } +fn load_db(path: &Path) -> Result> { + if path.as_os_str() == "-" { + let mut xml = String::new(); + std::io::stdin().read_to_string(&mut xml)?; + Ok(XtceDb::from_xml(&xml)?) + } else { + Ok(XtceDb::from_path(path)?) + } +} + fn run(cli: Cli) -> Result<(), Box> { match cli.command { - Command::Info { files, verbose } => { - let mut failures = 0; - for file in &files { - let started = Instant::now(); - match XtceDb::from_path(file) { - Ok(db) => info::report(&db, started.elapsed(), verbose), - Err(error) => { - failures += 1; - eprintln!("{}: {error}", file.display()); - } - } - } - if failures > 0 { - return Err(format!("{failures} of {} file(s) failed to load", files.len()).into()); - } - Ok(()) - } - + Command::Info { files, verbose } => run_info(&files, verbose), Command::Decode { definition, packets, @@ -145,6 +143,7 @@ fn run(cli: Cli) -> Result<(), Box> { params, format, raw, + no_summary, } => decode::run(&decode::Options { definition: &definition, packets: &packets, @@ -154,69 +153,105 @@ fn run(cli: Cli) -> Result<(), Box> { only: ¶ms, format, show_raw: raw, + no_summary, }), - Command::Codegen { definition, root, out, - } => { - let db = XtceDb::from_path(&definition)?; - let source = xtce_codegen::generate( - &db, - &xtce_codegen::Options { - root, - source_label: Some(definition.display().to_string()), - }, - )?; - match out { - Some(path) => { - std::fs::write(&path, source)?; - eprintln!("wrote {}", path.display()); - eprintln!( - "include it inside a module carrying the lint allowances generated \ - code needs; the file's header shows how" - ); - } - None => print!("{source}"), + } => run_codegen(&definition, root, out), + Command::Bench { file, iterations } => run_bench(&file, iterations), + } +} + +fn run_info(files: &[PathBuf], verbose: bool) -> Result<(), Box> { + let mut failures = 0; + for file in files { + let started = Instant::now(); + match load_db(file) { + Ok(db) => info::report(&db, started.elapsed(), verbose), + Err(error) => { + failures += 1; + eprintln!("{}: {error}", file.display()); } - Ok(()) } + } + if failures > 0 { + return Err(format!("{failures} of {} file(s) failed to load", files.len()).into()); + } + Ok(()) +} - Command::Bench { file, iterations } => { - let bytes = std::fs::metadata(&file).map_or(0, |meta| meta.len()); - let mut timings = Vec::with_capacity(iterations as usize); - let mut last = None; - for _ in 0..iterations.max(1) { - let started = Instant::now(); - let db = XtceDb::from_path(&file)?; - timings.push(started.elapsed()); - last = Some(db); - } - timings.sort_unstable(); - let median = timings.get(timings.len() / 2).copied().unwrap_or_default(); - let best = timings.first().copied().unwrap_or_default(); - - println!("{}", file.display()); - println!(" size {:>10.1} KiB", bytes as f64 / 1024.0); - println!(" load median {:>10.3} ms", median.as_secs_f64() * 1e3); - println!(" load best {:>10.3} ms", best.as_secs_f64() * 1e3); - if let Some(db) = last { - let stats = db.stats(); - println!( - " throughput {:>10.1} MiB/s", - (bytes as f64 / (1024.0 * 1024.0)) - / median.as_secs_f64().max(f64::MIN_POSITIVE) - ); - println!( - " model {} parameters, {} containers, {} interned names ({:.1} KiB)", - stats.parameters, - stats.containers, - stats.interned_names, - stats.interned_bytes as f64 / 1024.0 - ); - } - Ok(()) +fn run_codegen( + definition: &Path, + root: Option, + out: Option, +) -> Result<(), Box> { + let db = load_db(definition)?; + let source_label = if definition.as_os_str() == "-" { + Some("".to_owned()) + } else { + Some(definition.display().to_string()) + }; + let source = xtce_codegen::generate(&db, &xtce_codegen::Options { root, source_label })?; + match out { + Some(path) => { + std::fs::write(&path, source)?; + eprintln!("wrote {}", path.display()); + eprintln!( + "include it inside a module carrying the lint allowances generated \ + code needs; the file's header shows how" + ); } + None => print!("{source}"), + } + Ok(()) +} + +fn run_bench(file: &Path, iterations: u32) -> Result<(), Box> { + let (bytes, xml_data) = if file.as_os_str() == "-" { + let mut xml = String::new(); + std::io::stdin().read_to_string(&mut xml)?; + (xml.len() as u64, Some(xml)) + } else { + (std::fs::metadata(file).map_or(0, |meta| meta.len()), None) + }; + let mut timings = Vec::with_capacity(iterations as usize); + let mut last = None; + for _ in 0..iterations.max(1) { + let started = Instant::now(); + let db = match &xml_data { + Some(xml) => XtceDb::from_xml(xml)?, + None => XtceDb::from_path(file)?, + }; + timings.push(started.elapsed()); + last = Some(db); + } + timings.sort_unstable(); + let median = timings.get(timings.len() / 2).copied().unwrap_or_default(); + let best = timings.first().copied().unwrap_or_default(); + + if file.as_os_str() == "-" { + println!(""); + } else { + println!("{}", file.display()); + } + println!(" size {:>10.1} KiB", bytes as f64 / 1024.0); + println!(" load median {:>10.3} ms", median.as_secs_f64() * 1e3); + println!(" load best {:>10.3} ms", best.as_secs_f64() * 1e3); + if let Some(db) = last { + let stats = db.stats(); + println!( + " throughput {:>10.1} MiB/s", + (bytes as f64 / (1024.0 * 1024.0)) / median.as_secs_f64().max(f64::MIN_POSITIVE) + ); + println!( + " model {} parameters, {} containers, {} interned names ({:.1} KiB)", + stats.parameters, + stats.containers, + stats.interned_names, + stats.interned_bytes as f64 / 1024.0 + ); } + Ok(()) } From 84a53b7d2627785fb62067f109ec32e6fbd3927f Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Tue, 17 Nov 2026 15:46:42 +0100 Subject: [PATCH 02/13] feat(decode): stream packets via PacketReader without buffering whole streams Add PacketReader to stream CCSDS space packets sequentially from any std::io::Read source into an internal reusable buffer bounded at 64 KiB, eliminating unbounded memory consumption on large telemetry streams or live stdin feeds. Update xtce decode to stream packets on the fly via PacketReader, and add tests for streaming framing, wrappers, and stdin conflict rejection. --- crates/xtce-cli/src/decode.rs | 48 ++++-- crates/xtce-decode/src/ccsds.rs | 265 ++++++++++++++++++++++++++++++++ crates/xtce-decode/src/lib.rs | 2 +- 3 files changed, 300 insertions(+), 15 deletions(-) diff --git a/crates/xtce-cli/src/decode.rs b/crates/xtce-cli/src/decode.rs index dde4556..2d567a9 100644 --- a/crates/xtce-cli/src/decode.rs +++ b/crates/xtce-cli/src/decode.rs @@ -4,7 +4,7 @@ use std::io::{Read, Write}; use std::path::Path; use std::time::Instant; -use xtce_decode::{DecodeError, Decoder, EngValue, PacketIter, RawValue}; +use xtce_decode::{DecodeError, Decoder, EngValue, PacketReader, RawValue}; use xtce_model::XtceDb; /// How to render each packet. @@ -33,13 +33,12 @@ pub struct Options<'a> { pub no_summary: bool, } -fn load_stream(packets: &Path) -> std::io::Result> { +fn open_packet_source(packets: &Path) -> std::io::Result> { if packets.as_os_str() == "-" { - let mut bytes = Vec::new(); - std::io::stdin().read_to_end(&mut bytes)?; - Ok(bytes) + Ok(Box::new(std::io::BufReader::new(std::io::stdin()))) } else { - std::fs::read(packets) + let file = std::fs::File::open(packets)?; + Ok(Box::new(std::io::BufReader::new(file))) } } @@ -112,7 +111,8 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { None => Decoder::new(&db)?, }; - let stream = load_stream(options.packets)?; + let source = open_packet_source(options.packets)?; + let mut reader = PacketReader::new(source, options.skip_header_bytes); let stdout = std::io::stdout(); let mut out = std::io::BufWriter::new(stdout.lock()); @@ -122,9 +122,6 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { let mut trailing = 0usize; let mut total = 0usize; - // One packet buffer for the whole stream: after the first packet this allocates nothing. - let mut packet = decoder.new_packet(&stream); - if options.format == Format::Csv { if options.show_raw { writeln!(out, "packet,container,parameter,eng,raw")?; @@ -134,15 +131,15 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { } let decode_start = Instant::now(); - for (index, framed) in PacketIter::new(&stream, options.skip_header_bytes).enumerate() { + let mut index = 0usize; + while let Some(framed) = reader.next_packet()? { if options.limit.is_some_and(|limit| total >= limit) { break; } total += 1; - let framed = framed?; - match decoder.decode_into(&mut packet, framed.bytes()) { - Ok(()) => { + match decoder.decode(framed.bytes()) { + Ok(packet) => { decoded_count += 1; if packet.trailing_bits() != 0 { trailing += 1; @@ -176,6 +173,7 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { } } } + index += 1; } let decode_elapsed = decode_start.elapsed(); @@ -823,4 +821,26 @@ mod tests { assert!(text.contains("10 packet(s): 8 decoded, 1 not described, 1 failed")); assert!(text.contains("2 packet(s) had bits no entry claimed")); } + + #[test] + fn run_rejects_stdin_conflict_for_definition_and_packets() { + let options = super::Options { + definition: std::path::Path::new("-"), + packets: std::path::Path::new("-"), + root: None, + skip_header_bytes: 0, + limit: None, + only: &[], + format: super::Format::Quiet, + show_raw: false, + no_summary: true, + }; + let result = super::run(&options); + assert!(result.is_err()); + let err = result.unwrap_err(); + assert_eq!( + err.to_string(), + "cannot read both definition and packets from standard input" + ); + } } diff --git a/crates/xtce-decode/src/ccsds.rs b/crates/xtce-decode/src/ccsds.rs index fc36219..74ee34a 100644 --- a/crates/xtce-decode/src/ccsds.rs +++ b/crates/xtce-decode/src/ccsds.rs @@ -8,6 +8,7 @@ //! steps over it. The SUDA test file in this repository needs four. use std::fmt; +use std::io::Read; /// Size of the CCSDS primary header. pub const PRIMARY_HEADER_BYTES: usize = 6; @@ -199,6 +200,194 @@ impl<'a> Iterator for PacketIter<'a> { } } +/// An error encountered while reading a packet stream. +#[derive(Debug, thiserror::Error)] +pub enum PacketReadError { + /// A malformed packet frame in the stream. + #[error(transparent)] + Framing(#[from] FramingError), + + /// An I/O error reading from the underlying stream. + #[error("I/O error at stream offset {offset}: {source}")] + Io { + /// Byte offset in the stream where the error occurred. + offset: usize, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, +} + +/// Reads CCSDS space packets sequentially from an I/O source. +/// +/// Unlike [`PacketIter`], which borrows from an in-memory byte slice, `PacketReader` +/// streams packets from any [`Read`] source into an internal reusable buffer, +/// allocating at most one maximum-length packet buffer (up to 64 KiB) regardless of stream +/// size. +/// +/// ```no_run +/// # fn main() -> Result<(), Box> { +/// use std::fs::File; +/// use std::io::BufReader; +/// use xtce_decode::ccsds::PacketReader; +/// +/// let file = File::open("telemetry.bin")?; +/// let mut reader = PacketReader::new(BufReader::new(file), 0); +/// while let Some(packet) = reader.next_packet()? { +/// println!("APID: {}", packet.apid()); +/// } +/// # Ok(()) +/// # } +/// ``` +pub struct PacketReader { + reader: R, + offset: usize, + skip_header_bytes: usize, + buffer: Vec, + finished: bool, +} + +impl fmt::Debug for PacketReader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("PacketReader") + .field("offset", &self.offset) + .field("skip_header_bytes", &self.skip_header_bytes) + .field("buffer_len", &self.buffer.len()) + .field("finished", &self.finished) + .finish_non_exhaustive() + } +} + +impl PacketReader { + /// Creates a new `PacketReader` reading from `reader`, skipping `skip_header_bytes` before each packet. + #[must_use] + pub const fn new(reader: R, skip_header_bytes: usize) -> Self { + Self { + reader, + offset: 0, + skip_header_bytes, + buffer: Vec::new(), + finished: false, + } + } + + /// Current byte offset in the underlying stream. + #[must_use] + pub const fn offset(&self) -> usize { + self.offset + } + + /// Consumes the `PacketReader`, returning the underlying reader. + #[must_use] + pub fn into_inner(self) -> R { + self.reader + } + + /// Reads the next CCSDS packet from the stream into an internal buffer. + /// + /// Returns `Ok(Some(packet))` on success, `Ok(None)` on clean EOF, or `Err(...)` on framing or I/O error. + /// + /// # Errors + /// + /// Yields [`PacketReadError::Framing`] if the stream ends mid-packet, or + /// [`PacketReadError::Io`] if an I/O error occurs on the reader. + pub fn next_packet(&mut self) -> Result>, PacketReadError> { + if self.finished { + return Ok(None); + } + + // 1. Skip wrapper bytes if configured. + let mut skipped = 0; + let mut skip_buf = [0u8; 64]; + while skipped < self.skip_header_bytes { + let to_read = (self.skip_header_bytes - skipped).min(skip_buf.len()); + match self.reader.read(&mut skip_buf[..to_read]) { + Ok(0) => { + self.offset += skipped; + self.finished = true; + return Ok(None); + } + Ok(n) => { + skipped += n; + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(source) => { + return Err(PacketReadError::Io { + offset: self.offset + skipped, + source, + }); + } + } + } + self.offset += skipped; + + let start_offset = self.offset; + + // 2. Read the primary CCSDS header (6 bytes). + self.buffer.resize(PRIMARY_HEADER_BYTES, 0); + let mut header_read = 0; + while header_read < PRIMARY_HEADER_BYTES { + match self + .reader + .read(&mut self.buffer[header_read..PRIMARY_HEADER_BYTES]) + { + Ok(0) => { + self.finished = true; + if header_read == 0 { + return Ok(None); + } + return Err(PacketReadError::Framing(FramingError::ShortHeader { + offset: start_offset, + remaining: header_read, + })); + } + Ok(n) => { + header_read += n; + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(source) => { + return Err(PacketReadError::Io { + offset: start_offset + header_read, + source, + }); + } + } + } + + // 3. Parse length and read packet payload. + let count = u16::from_be_bytes([self.buffer[4], self.buffer[5]]); + let total = PRIMARY_HEADER_BYTES + usize::from(count) + 1; + + self.buffer.resize(total, 0); + let mut total_read = PRIMARY_HEADER_BYTES; + while total_read < total { + match self.reader.read(&mut self.buffer[total_read..total]) { + Ok(0) => { + self.finished = true; + return Err(PacketReadError::Framing(FramingError::ShortPacket { + offset: start_offset, + declared: total, + remaining: total_read, + })); + } + Ok(n) => { + total_read += n; + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(source) => { + return Err(PacketReadError::Io { + offset: start_offset + total_read, + source, + }); + } + } + } + + self.offset = start_offset + total; + Ok(Some(SpacePacketBytes::new(&self.buffer))) + } +} + #[cfg(test)] mod tests { use super::*; @@ -286,4 +475,80 @@ mod tests { assert_eq!(packet.sequence_count(), 0x1234); assert_eq!(packet.data_length(), 1); } + + #[test] + fn packet_reader_splits_a_stream_into_packets() { + let mut stream = packet(11, 10); + stream.extend(packet(42, 4)); + + let mut reader = PacketReader::new(std::io::Cursor::new(stream), 0); + let p1 = reader.next_packet().expect("packet 1").expect("some"); + assert_eq!(p1.apid(), 11); + assert_eq!(p1.bytes().len(), 16); + assert_eq!(p1.user_data().len(), 10); + assert!(p1.secondary_header_flag()); + + let p2 = reader.next_packet().expect("packet 2").expect("some"); + assert_eq!(p2.apid(), 42); + assert_eq!(p2.bytes().len(), 10); + + assert!(reader.next_packet().expect("eof").is_none()); + assert_eq!(reader.offset(), 26); + } + + #[test] + fn packet_reader_skips_per_packet_wrappers() { + let mut stream = vec![0xDE, 0xAD, 0xBE, 0xEF]; + stream.extend(packet(7, 3)); + stream.extend([0xDE, 0xAD, 0xBE, 0xEF]); + stream.extend(packet(8, 3)); + + let mut reader = PacketReader::new(std::io::Cursor::new(stream), 4); + let p1 = reader.next_packet().expect("packet 1").expect("some"); + assert_eq!(p1.apid(), 7); + + let p2 = reader.next_packet().expect("packet 2").expect("some"); + assert_eq!(p2.apid(), 8); + + assert!(reader.next_packet().expect("eof").is_none()); + } + + #[test] + fn packet_reader_reports_truncated_tails() { + let mut stream = packet(11, 10); + stream.truncate(12); + let mut reader = PacketReader::new(std::io::Cursor::new(stream), 0); + let err = reader.next_packet().expect_err("truncated payload"); + assert!(matches!( + err, + PacketReadError::Framing(FramingError::ShortPacket { + offset: 0, + declared: 16, + remaining: 12, + }) + )); + + let stub = [0u8; 3]; + let mut reader = PacketReader::new(std::io::Cursor::new(stub), 0); + let err = reader.next_packet().expect_err("truncated header"); + assert!(matches!( + err, + PacketReadError::Framing(FramingError::ShortHeader { + offset: 0, + remaining: 3, + }) + )); + } + + #[test] + fn packet_reader_empty_stream_yields_nothing() { + let mut reader = PacketReader::new(std::io::Cursor::new([]), 0); + assert!(reader.next_packet().expect("ok").is_none()); + + let mut reader_wrapped = PacketReader::new(std::io::Cursor::new([0xAA; 4]), 4); + assert!(reader_wrapped.next_packet().expect("ok").is_none()); + + let mut reader_partial_wrap = PacketReader::new(std::io::Cursor::new([0xAA; 2]), 4); + assert!(reader_partial_wrap.next_packet().expect("ok").is_none()); + } } diff --git a/crates/xtce-decode/src/lib.rs b/crates/xtce-decode/src/lib.rs index 2bb5896..2881167 100644 --- a/crates/xtce-decode/src/lib.rs +++ b/crates/xtce-decode/src/lib.rs @@ -69,7 +69,7 @@ pub mod error; pub mod value; pub use bits::{BitCursor, BitError}; -pub use ccsds::{FramingError, PacketIter, SpacePacketBytes}; +pub use ccsds::{FramingError, PacketIter, PacketReadError, PacketReader, SpacePacketBytes}; pub use decoder::Decoder; pub use error::DecodeError; pub use value::{DecodedPacket, EngValue, ParameterValue, RawValue}; From 62d25d8ad51f2868dc4a8cf420a320b729b988f7 Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Tue, 17 Nov 2026 16:09:17 +0100 Subject: [PATCH 03/13] perf(cli): optimize CSV string escaping and bound stdin definition reads Emit byte slices instead of per-character writes in write_csv_string to avoid repeated I/O calls when escaping CSV fields. Cap standard input XML definition reads at 256 MiB to guard against unbounded stream inputs without impacting legitimate definitions. --- crates/xtce-cli/src/decode.rs | 20 +++++++++++++------- crates/xtce-cli/src/main.rs | 10 ++++++++-- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/crates/xtce-cli/src/decode.rs b/crates/xtce-cli/src/decode.rs index 2d567a9..a0c0ebb 100644 --- a/crates/xtce-cli/src/decode.rs +++ b/crates/xtce-cli/src/decode.rs @@ -42,10 +42,14 @@ fn open_packet_source(packets: &Path) -> std::io::Result> { } } +const MAX_DEFINITION_BYTES: u64 = 256 * 1024 * 1024; + fn load_definition(definition: &Path) -> Result> { if definition.as_os_str() == "-" { let mut xml = String::new(); - std::io::stdin().read_to_string(&mut xml)?; + std::io::stdin() + .take(MAX_DEFINITION_BYTES) + .read_to_string(&mut xml)?; Ok(XtceDb::from_xml(&xml)?) } else { Ok(XtceDb::from_path(definition)?) @@ -527,14 +531,16 @@ fn write_hex_raw(out: &mut impl Write, bytes: &[u8]) -> std::io::Result<()> { fn write_csv_string(out: &mut impl Write, text: &str) -> std::io::Result<()> { if text.contains([',', '"', '\n', '\r']) { out.write_all(b"\"")?; - for ch in text.chars() { - if ch == '"' { - out.write_all(b"\"\"")?; - } else { - let mut buf = [0u8; 4]; - out.write_all(ch.encode_utf8(&mut buf).as_bytes())?; + let bytes = text.as_bytes(); + let mut last = 0; + for (i, &b) in bytes.iter().enumerate() { + if b == b'"' { + out.write_all(&bytes[last..=i])?; + out.write_all(b"\"")?; + last = i + 1; } } + out.write_all(&bytes[last..])?; out.write_all(b"\"") } else { out.write_all(text.as_bytes()) diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index 274d5ce..38f5f5a 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -121,10 +121,14 @@ fn main() -> ExitCode { } } +const MAX_DEFINITION_BYTES: u64 = 256 * 1024 * 1024; + fn load_db(path: &Path) -> Result> { if path.as_os_str() == "-" { let mut xml = String::new(); - std::io::stdin().read_to_string(&mut xml)?; + std::io::stdin() + .take(MAX_DEFINITION_BYTES) + .read_to_string(&mut xml)?; Ok(XtceDb::from_xml(&xml)?) } else { Ok(XtceDb::from_path(path)?) @@ -211,7 +215,9 @@ fn run_codegen( fn run_bench(file: &Path, iterations: u32) -> Result<(), Box> { let (bytes, xml_data) = if file.as_os_str() == "-" { let mut xml = String::new(); - std::io::stdin().read_to_string(&mut xml)?; + std::io::stdin() + .take(MAX_DEFINITION_BYTES) + .read_to_string(&mut xml)?; (xml.len() as u64, Some(xml)) } else { (std::fs::metadata(file).map_or(0, |meta| meta.len()), None) From f9fb0678d46e345ff6cb66e67b3695d85fa4cdb0 Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Wed, 18 Nov 2026 13:57:22 +0100 Subject: [PATCH 04/13] feat(cli): add Wireshark Lua dissector generator and PCAP converter Add 'xtce wireshark' to compile an XTCE definition into a standalone Wireshark Lua dissector script covering container inheritance, restriction criteria, bit-level field extraction, enumerations, and polynomial calibration. Add 'xtce pcap' to stream concatenated CCSDS space packets into a standard libpcap (.pcap) capture file (DLT_USER0 = 147) with constant O(1) memory usage. --- crates/xtce-cli/src/main.rs | 73 ++++ crates/xtce-cli/src/pcap.rs | 247 ++++++++++++ crates/xtce-cli/src/wireshark.rs | 634 +++++++++++++++++++++++++++++++ 3 files changed, 954 insertions(+) create mode 100644 crates/xtce-cli/src/pcap.rs create mode 100644 crates/xtce-cli/src/wireshark.rs diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index 38f5f5a..13fb308 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -21,6 +21,8 @@ use xtce_model::XtceDb; mod decode; mod info; +mod pcap; +mod wireshark; #[derive(Parser)] #[command(name = "xtce", version, about, long_about = None)] @@ -95,6 +97,42 @@ enum Command { out: Option, }, + /// Compile a definition into a Wireshark Lua dissector script (.lua). + Wireshark { + /// XTCE definition. Use '-' to read from standard input. + definition: PathBuf, + + /// Container to start from. + #[arg(long)] + root: Option, + + /// Write here instead of standard output. + #[arg(long, short)] + out: Option, + + /// Also register the dissector on this UDP port in addition to DLT_USER0 (147). + #[arg(long)] + udp_port: Option, + }, + + /// Wrap a raw CCSDS packet stream in a libpcap (.pcap) capture file for Wireshark. + Pcap { + /// File of concatenated CCSDS packets. Use '-' to read from standard input. + packets: PathBuf, + + /// Write here instead of standard output. + #[arg(long, short)] + out: Option, + + /// Bytes of per-packet wrapper to skip before each CCSDS header. + #[arg(long, default_value_t = 0)] + skip_header_bytes: usize, + + /// Stop after this many packets. + #[arg(long)] + limit: Option, + }, + /// Time loading an XTCE file. Bench { /// XTCE file to load. Use '-' to read from standard input. @@ -164,10 +202,45 @@ fn run(cli: Cli) -> Result<(), Box> { root, out, } => run_codegen(&definition, root, out), + Command::Wireshark { + definition, + root, + out, + udp_port, + } => run_wireshark(&definition, root.as_deref(), out.as_deref(), udp_port), + Command::Pcap { + packets, + out, + skip_header_bytes, + limit, + } => pcap::run(&pcap::Options { + packets: &packets, + out: out.as_deref(), + skip_header_bytes, + limit, + }), Command::Bench { file, iterations } => run_bench(&file, iterations), } } +fn run_wireshark( + definition: &Path, + root: Option<&str>, + out: Option<&Path>, + udp_port: Option, +) -> Result<(), Box> { + let db = load_db(definition)?; + wireshark::run_with_db( + &db, + &wireshark::Options { + definition, + root, + out, + udp_port, + }, + ) +} + fn run_info(files: &[PathBuf], verbose: bool) -> Result<(), Box> { let mut failures = 0; for file in files { diff --git a/crates/xtce-cli/src/pcap.rs b/crates/xtce-cli/src/pcap.rs new file mode 100644 index 0000000..3354755 --- /dev/null +++ b/crates/xtce-cli/src/pcap.rs @@ -0,0 +1,247 @@ +//! `xtce pcap` — wrap a CCSDS space packet stream in a libpcap (`.pcap`) capture file. +//! +//! Wireshark and `tshark` dissect raw space packets over the `USER0` data-link type +//! (`DLT_USER0 = 147`). Writing a standard 24-byte global header and a 16-byte record header +//! around each framed CCSDS packet lets an engineer open any telemetry recording directly in +//! Wireshark alongside the Lua dissector produced by `xtce wireshark`. + +use std::io::{Read, Write}; +use std::path::Path; + +use xtce_decode::{PacketReadError, PacketReader}; + +/// Standard libpcap magic number for microsecond-resolution little-endian captures. +#[cfg(test)] +pub const PCAP_MAGIC_LE: u32 = 0xA1B2_C3D4; + +/// `DLT_USER0` (147), the conventional link-layer header type for raw CCSDS packets. +#[cfg(test)] +pub const LINKTYPE_USER0: u32 = 147; + +/// Maximum packet length advertised in the PCAP global header. +const SNAPLEN: u32 = 65_535; + +/// Pre-encoded 24-byte little-endian PCAP global header (version 2.4, `LINKTYPE_USER0`). +const GLOBAL_HEADER: [u8; 24] = [ + 0xD4, 0xC3, 0xB2, 0xA1, // magic_number: 0xa1b2c3d4 + 0x02, 0x00, // version_major: 2 + 0x04, 0x00, // version_minor: 4 + 0x00, 0x00, 0x00, 0x00, // thiszone: 0 + 0x00, 0x00, 0x00, 0x00, // sigfigs: 0 + 0xFF, 0xFF, 0x00, 0x00, // snaplen: 65535 + 0x93, 0x00, 0x00, 0x00, // network: 147 (LINKTYPE_USER0) +]; + +/// Configuration for `xtce pcap`. +pub struct Options<'a> { + pub packets: &'a Path, + pub out: Option<&'a Path>, + pub skip_header_bytes: usize, + pub limit: Option, +} + +/// Summary of packets written to a PCAP stream. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Stats { + pub packets: usize, + pub payload_bytes: u64, +} + +fn open_packet_source(packets: &Path) -> std::io::Result> { + if packets.as_os_str() == "-" { + Ok(Box::new(std::io::BufReader::new(std::io::stdin()))) + } else { + let file = std::fs::File::open(packets)?; + Ok(Box::new(std::io::BufReader::new(file))) + } +} + +/// Streams packets from `reader` into `out` formatted as a libpcap capture. +/// +/// Synthetic timestamps advance by 1 millisecond per packet so that Wireshark I/O graphs and +/// timeline filters have a monotonic time axis even when the raw recording carries no ground +/// receipt timestamps. +/// +/// # Errors +/// +/// Returns [`PacketReadError::Framing`] if the input stream ends mid-packet, or +/// [`PacketReadError::Io`] if reading or writing fails. +pub fn write_stream( + reader: &mut PacketReader, + out: &mut W, + limit: Option, +) -> Result { + out.write_all(&GLOBAL_HEADER) + .map_err(|source| PacketReadError::Io { offset: 0, source })?; + + let mut stats = Stats::default(); + + while let Some(framed) = reader.next_packet()? { + if limit.is_some_and(|max| stats.packets >= max) { + break; + } + + let bytes = framed.bytes(); + let pkt_len = u32::try_from(bytes.len()).unwrap_or(u32::MAX); + let index_u32 = u32::try_from(stats.packets).unwrap_or(u32::MAX); + let seconds = index_u32 / 1_000; + let micros = (index_u32 % 1_000) * 1_000; + + let s = seconds.to_le_bytes(); + let u = micros.to_le_bytes(); + let inc = pkt_len.min(SNAPLEN).to_le_bytes(); + let orig = pkt_len.to_le_bytes(); + + let record_header: [u8; 16] = [ + s[0], s[1], s[2], s[3], u[0], u[1], u[2], u[3], inc[0], inc[1], inc[2], inc[3], + orig[0], orig[1], orig[2], orig[3], + ]; + + let write_len = (pkt_len.min(SNAPLEN)) as usize; + out.write_all(&record_header) + .and_then(|()| out.write_all(&bytes[..write_len])) + .map_err(|source| PacketReadError::Io { + offset: reader.offset(), + source, + })?; + + stats.packets += 1; + stats.payload_bytes += write_len as u64; + } + + Ok(stats) +} + +/// Executes `xtce pcap`. +/// +/// # Errors +/// +/// Returns an error if the packet source or output destination cannot be opened, or if the +/// packet stream is malformed. +pub fn run(options: &Options<'_>) -> Result<(), Box> { + let source = open_packet_source(options.packets)?; + let mut reader = PacketReader::new(source, options.skip_header_bytes); + + match options.out { + Some(path) if path.as_os_str() != "-" => { + let file = std::fs::File::create(path)?; + let mut out = std::io::BufWriter::new(file); + let stats = write_stream(&mut reader, &mut out, options.limit)?; + out.flush()?; + eprintln!( + "wrote {} packet(s) ({} payload bytes) to {}", + stats.packets, + stats.payload_bytes, + path.display() + ); + } + _ => { + let stdout = std::io::stdout(); + let mut out = std::io::BufWriter::new(stdout.lock()); + let stats = write_stream(&mut reader, &mut out, options.limit)?; + out.flush()?; + eprintln!( + "wrote {} packet(s) ({} payload bytes) to ", + stats.packets, stats.payload_bytes + ); + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::io::Cursor; + + use xtce_decode::{FramingError, PacketReadError, PacketReader}; + + use super::{GLOBAL_HEADER, LINKTYPE_USER0, PCAP_MAGIC_LE, write_stream}; + + fn make_packet(apid: u16, payload: &[u8]) -> Vec { + let mut pkt = Vec::with_capacity(6 + payload.len()); + let word0 = 0x0800 | (apid & 0x07FF); + pkt.extend_from_slice(&word0.to_be_bytes()); + pkt.extend_from_slice(&0xC000u16.to_be_bytes()); + let len_field = u16::try_from(payload.len().saturating_sub(1)).unwrap_or(0); + pkt.extend_from_slice(&len_field.to_be_bytes()); + pkt.extend_from_slice(payload); + pkt + } + + #[test] + fn writes_valid_pcap_global_and_packet_headers() { + let mut raw = make_packet(0x10, &[1, 2, 3, 4]); + raw.extend(make_packet(0x20, &[5, 6])); + + let mut reader = PacketReader::new(Cursor::new(raw), 0); + let mut out = Vec::new(); + let stats = write_stream(&mut reader, &mut out, None).expect("pcap writes"); + + assert_eq!(stats.packets, 2); + assert_eq!(stats.payload_bytes, 18); + assert_eq!(out.len(), 24 + (16 + 10) + (16 + 8)); + + let magic = u32::from_le_bytes(out[0..4].try_into().unwrap()); + let linktype = u32::from_le_bytes(out[20..24].try_into().unwrap()); + assert_eq!(magic, PCAP_MAGIC_LE); + assert_eq!(linktype, LINKTYPE_USER0); + + // First packet record header at offset 24: ts_sec=0, ts_usec=0, incl_len=10, orig_len=10 + assert_eq!(u32::from_le_bytes(out[24..28].try_into().unwrap()), 0); + assert_eq!(u32::from_le_bytes(out[28..32].try_into().unwrap()), 0); + assert_eq!(u32::from_le_bytes(out[32..36].try_into().unwrap()), 10); + assert_eq!(u32::from_le_bytes(out[36..40].try_into().unwrap()), 10); + + // Second packet record header at offset 50: ts_sec=0, ts_usec=1000, incl_len=8, orig_len=8 + assert_eq!(u32::from_le_bytes(out[50..54].try_into().unwrap()), 0); + assert_eq!(u32::from_le_bytes(out[54..58].try_into().unwrap()), 1_000); + assert_eq!(u32::from_le_bytes(out[58..62].try_into().unwrap()), 8); + assert_eq!(u32::from_le_bytes(out[62..66].try_into().unwrap()), 8); + } + + #[test] + fn respects_packet_limit_and_skip_header_bytes() { + let mut raw = vec![0xAA, 0xBB, 0xCC, 0xDD]; + raw.extend(make_packet(1, &[0x11, 0x22])); + raw.extend([0xAA, 0xBB, 0xCC, 0xDD]); + raw.extend(make_packet(2, &[0x33, 0x44])); + + let mut reader = PacketReader::new(Cursor::new(raw), 4); + let mut out = Vec::new(); + let stats = write_stream(&mut reader, &mut out, Some(1)).expect("limited pcap"); + + assert_eq!(stats.packets, 1); + assert_eq!(stats.payload_bytes, 8); + assert_eq!(out.len(), 24 + 16 + 8); + } + + #[test] + fn empty_stream_writes_only_global_header() { + let mut reader = PacketReader::new(Cursor::new(Vec::::new()), 0); + let mut out = Vec::new(); + let stats = write_stream(&mut reader, &mut out, None).expect("empty pcap"); + + assert_eq!(stats.packets, 0); + assert_eq!(stats.payload_bytes, 0); + assert_eq!(out.as_slice(), &GLOBAL_HEADER); + } + + #[test] + fn truncated_packet_surfaces_framing_error() { + let mut raw = make_packet(1, &[1, 2, 3, 4]); + raw.truncate(8); + + let mut reader = PacketReader::new(Cursor::new(raw), 0); + let mut out = Vec::new(); + let err = write_stream(&mut reader, &mut out, None).expect_err("truncated"); + assert!(matches!( + err, + PacketReadError::Framing(FramingError::ShortPacket { + offset: 0, + declared: 10, + remaining: 8, + }) + )); + } +} diff --git a/crates/xtce-cli/src/wireshark.rs b/crates/xtce-cli/src/wireshark.rs new file mode 100644 index 0000000..4867230 --- /dev/null +++ b/crates/xtce-cli/src/wireshark.rs @@ -0,0 +1,634 @@ +//! `xtce wireshark` — compile an XTCE definition into a Wireshark Lua dissector (`.lua`). +//! +//! During spacecraft bench integration (FlatSat / EGSE), engineers inspect live UDP telemetry +//! or recorded `.pcap` files in Wireshark. Hand-maintaining Lua dissectors whenever the +//! telemetry database changes is tedious and error-prone; this module compiles the XTCE +//! container hierarchy, restriction criteria, bit offsets, enumerations, and polynomial +//! calibrators directly into a standalone Wireshark Lua script. + +use std::collections::BTreeSet; +use std::fmt::Write as _; +use std::path::Path; + +use xtce_codegen::{ + Calibration, CodegenError, ContainerPlan, Criterion, Field, Guard, GuardTest, Node, Plan, Repr, +}; +use xtce_model::{CompareOp, IntegerCoding, XtceDb}; + +/// Configuration for `xtce wireshark`. +pub struct Options<'a> { + pub definition: &'a Path, + pub root: Option<&'a str>, + pub out: Option<&'a Path>, + pub udp_port: Option, +} + +/// Compiles `db` into a Wireshark Lua dissector script. +/// +/// # Errors +/// +/// Returns [`CodegenError`] if the root container cannot be resolved or if the definition uses +/// constructs outside the compilable subset. +pub fn generate_lua( + db: &XtceDb, + root: Option<&str>, + source_label: &str, + udp_port: Option, +) -> Result { + let plan = xtce_codegen::plan( + db, + &xtce_codegen::Options { + root: root.map(str::to_owned), + source_label: Some(source_label.to_owned()), + }, + )?; + + Ok(emit_lua(&plan, source_label, udp_port)) +} + +fn emit_lua(plan: &Plan, source_label: &str, udp_port: Option) -> String { + let mut out = String::with_capacity(8192); + let proto_name = sanitise_proto_name(&plan.root_name); + + emit_header(&mut out, source_label, &plan.root_name, &proto_name); + emit_proto_fields(&mut out, plan, &proto_name); + emit_bit_helpers(&mut out); + emit_container_dissectors(&mut out, &plan.containers); + emit_dispatcher(&mut out, &plan.root, &plan.containers); + emit_registration(&mut out, &proto_name, udp_port); + + out +} + +fn emit_header(out: &mut String, source_label: &str, root_name: &str, proto_name: &str) { + let _ = writeln!( + out, + "-- Generated by `xtce wireshark` from {source_label} (root: {root_name})." + ); + let _ = writeln!( + out, + "-- Do not edit by hand; regenerate from the XTCE definition." + ); + let _ = writeln!(out, "--"); + let _ = writeln!(out, "-- Quick start:"); + let _ = writeln!(out, "-- xtce pcap telemetry.bin -o telemetry.pcap"); + let _ = writeln!( + out, + "-- wireshark -X lua_script:{proto_name}.lua telemetry.pcap\n" + ); + let _ = write!(out, "local proto = Proto(\"{proto_name}\", "); + write_lua_quoted(out, root_name); + let _ = writeln!(out, ")\n"); +} + +fn emit_proto_fields(out: &mut String, plan: &Plan, proto_name: &str) { + let _ = writeln!( + out, + "local f__container = ProtoField.string(\"{proto_name}.container\", \"Container\")" + ); + + let mut seen: BTreeSet<&str> = BTreeSet::new(); + let mut field_vars: Vec<(&str, bool)> = Vec::new(); + + for container in &plan.containers { + for field in &container.fields { + if !seen.insert(field.ident.as_str()) { + continue; + } + let kind = lua_proto_field_kind(&field.repr); + let _ = write!( + out, + "local f_{} = ProtoField.{kind}(\"{proto_name}.{}\", ", + field.ident, field.ident + ); + write_lua_quoted(out, &field.xtce_name); + if matches!(field.repr, Repr::Unsigned | Repr::Signed(_)) { + let _ = writeln!(out, ", base.DEC)"); + } else { + let _ = writeln!(out, ")"); + } + + let has_eng = field.calibration.is_some(); + if has_eng { + let _ = write!( + out, + "local f_{}_eng = ProtoField.double(\"{proto_name}.{}.eng\", ", + field.ident, field.ident + ); + write_lua_quoted(out, &field.xtce_name); + let _ = writeln!(out, ")"); + } + field_vars.push((field.ident.as_str(), has_eng)); + } + } + + let _ = writeln!(out, "\nproto.fields = {{"); + let _ = writeln!(out, " f__container,"); + for (ident, has_eng) in &field_vars { + let _ = writeln!(out, " f_{ident},"); + if *has_eng { + let _ = writeln!(out, " f_{ident}_eng,"); + } + } + let _ = writeln!(out, "}}\n"); +} + +const fn lua_proto_field_kind(repr: &Repr) -> &'static str { + match repr { + Repr::Unsigned => "uint64", + Repr::Signed(_) => "int64", + Repr::Float16 | Repr::Float32 | Repr::Float64 | Repr::Mil1750a => "double", + Repr::Bool => "bool", + Repr::Enumerated(_) | Repr::Text { .. } => "string", + Repr::Binary => "bytes", + } +} + +fn emit_bit_helpers(out: &mut String) { + out.push_str( + r"local function has_bits(tvbuf, bit_offset, bit_width) + return (bit_offset + bit_width) <= (tvbuf:len() * 8) +end + +local function byte_range(tvbuf, bit_offset, bit_width) + if bit_width == 0 then + return tvbuf:range(0, 0) + end + local start_byte = math.floor(bit_offset / 8) + local end_byte = math.floor((bit_offset + bit_width - 1) / 8) + return tvbuf:range(start_byte, end_byte - start_byte + 1) +end + +local function read_bits_uint(tvbuf, bit_offset, bit_width, swap_bytes) + local acc = 0 + for i = 0, bit_width - 1 do + local pos = bit_offset + i + local byte_idx = math.floor(pos / 8) + local bit_idx = 7 - (pos % 8) + local b = tvbuf:range(byte_idx, 1):uint() + local bit_val = math.floor(b / (2 ^ bit_idx)) % 2 + acc = acc * 2 + bit_val + end + if swap_bytes and bit_width >= 16 and (bit_width % 8 == 0) then + local nbytes = bit_width / 8 + local swapped = 0 + for _ = 1, nbytes do + swapped = swapped * 256 + (acc % 256) + acc = math.floor(acc / 256) + end + return swapped + end + return acc +end + +local function read_bits_int(tvbuf, bit_offset, bit_width, swap_bytes) + local raw = read_bits_uint(tvbuf, bit_offset, bit_width, swap_bytes) + local sign_bit = 2 ^ (bit_width - 1) + if raw >= sign_bit then + return raw - (2 ^ bit_width) + end + return raw +end + +", + ); +} + +fn emit_container_dissectors(out: &mut String, containers: &[ContainerPlan]) { + for container in containers { + let _ = writeln!( + out, + "local function dissect_{}(tvbuf, pinfo, subtree)", + container.type_ident + ); + let _ = write!(out, " pinfo.cols.info:set("); + write_lua_quoted(out, &container.xtce_name); + let _ = writeln!(out, ")"); + let _ = write!( + out, + " subtree:add(f__container, tvbuf:range(0, tvbuf:len()), " + ); + write_lua_quoted(out, &container.xtce_name); + let _ = writeln!(out, ")"); + + for field in &container.fields { + emit_field_dissection(out, field); + } + + let _ = writeln!(out, "end\n"); + } +} + +fn emit_field_dissection(out: &mut String, field: &Field) { + let Some((bit_offset, bit_width)) = field.static_span() else { + return; + }; + if bit_width == 0 { + return; + } + + let swap = if field.swap_bytes { "true" } else { "false" }; + let ident = &field.ident; + let _ = writeln!( + out, + " if has_bits(tvbuf, {bit_offset}, {bit_width}) then" + ); + let _ = writeln!( + out, + " local rng = byte_range(tvbuf, {bit_offset}, {bit_width})" + ); + + match &field.repr { + Repr::Unsigned => { + let _ = writeln!( + out, + " local raw = read_bits_uint(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, UInt64.new(raw))"); + emit_calibration(out, field); + } + Repr::Signed(IntegerCoding::TwosComplement) => { + let _ = writeln!( + out, + " local raw = read_bits_int(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, Int64.new(raw))"); + emit_calibration(out, field); + } + Repr::Signed(_) => { + let _ = writeln!( + out, + " local raw = read_bits_uint(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, Int64.new(raw))"); + emit_calibration(out, field); + } + Repr::Bool => { + let _ = writeln!( + out, + " local raw = read_bits_uint(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, raw ~= 0)"); + } + Repr::Enumerated(entries) => { + let _ = writeln!( + out, + " local raw = read_bits_int(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " local label = tostring(raw)"); + for (low, high, label) in entries { + if low == high { + let _ = write!(out, " if raw == {low} then label = "); + } else { + let _ = write!( + out, + " if raw >= {low} and raw <= {high} then label = " + ); + } + write_lua_quoted(out, label); + let _ = writeln!(out, " .. \" (\" .. tostring(raw) .. \")\" end"); + } + let _ = writeln!(out, " subtree:add(f_{ident}, rng, label)"); + } + Repr::Float32 | Repr::Float64 if bit_offset % 8 == 0 && !field.swap_bytes => { + let _ = writeln!(out, " local raw = rng:float()"); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, raw)"); + emit_calibration(out, field); + } + Repr::Float16 | Repr::Float32 | Repr::Float64 | Repr::Mil1750a => { + let _ = writeln!( + out, + " local raw = read_bits_uint(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, raw)"); + emit_calibration(out, field); + } + Repr::Text { .. } => { + let _ = writeln!(out, " subtree:add(f_{ident}, rng, rng:string())"); + } + Repr::Binary => { + let _ = writeln!(out, " subtree:add(f_{ident}, rng)"); + } + } + + let _ = writeln!(out, " end"); +} + +fn emit_calibration(out: &mut String, field: &Field) { + let Some(Calibration::Polynomial(terms)) = &field.calibration else { + return; + }; + if terms.is_empty() { + return; + } + let _ = write!(out, " local eng = 0.0"); + for term in terms { + let c = term.coefficient; + let e = term.exponent; + let _ = write!(out, " + ({c:?} * (raw ^ {e}))"); + } + let _ = writeln!(out); + let _ = writeln!(out, " subtree:add(f_{}_eng, rng, eng)", field.ident); +} + +fn emit_dispatcher(out: &mut String, root: &Node, containers: &[ContainerPlan]) { + let _ = writeln!(out, "local function dispatch(tvbuf, pinfo, subtree)"); + emit_node_dispatch(out, root, containers, 1); + let _ = writeln!(out, " return false"); + let _ = writeln!(out, "end\n"); +} + +fn emit_node_dispatch(out: &mut String, node: &Node, containers: &[ContainerPlan], depth: usize) { + for (criterion, child) in &node.children { + write_indent(out, depth); + let _ = write!(out, "if "); + emit_criterion_expr(out, criterion); + let _ = writeln!(out, " then"); + emit_node_dispatch(out, child, containers, depth + 1); + write_indent(out, depth); + let _ = writeln!(out, "end"); + } + + if !node.is_abstract { + if let Some(idx) = node.plan { + if let Some(plan) = containers.get(idx) { + write_indent(out, depth); + let _ = writeln!(out, "dissect_{}(tvbuf, pinfo, subtree)", plan.type_ident); + write_indent(out, depth); + let _ = writeln!(out, "return true"); + } + } + } +} + +fn emit_criterion_expr(out: &mut String, criterion: &Criterion) { + match criterion { + Criterion::Test(guard) => emit_guard_expr(out, guard), + Criterion::All(children) => { + if children.is_empty() { + out.push_str("true"); + return; + } + out.push('('); + for (idx, child) in children.iter().enumerate() { + if idx > 0 { + out.push_str(" and "); + } + emit_criterion_expr(out, child); + } + out.push(')'); + } + Criterion::Any(children) => { + if children.is_empty() { + out.push_str("false"); + return; + } + out.push('('); + for (idx, child) in children.iter().enumerate() { + if idx > 0 { + out.push_str(" or "); + } + emit_criterion_expr(out, child); + } + out.push(')'); + } + } +} + +fn emit_guard_expr(out: &mut String, guard: &Guard) { + let offset = guard.bit_offset; + let width = guard.bit_width; + let swap = if guard.swap_bytes { "true" } else { "false" }; + let reader = if matches!(guard.repr, Repr::Signed(_)) { + "read_bits_int" + } else { + "read_bits_uint" + }; + + let _ = write!(out, "(has_bits(tvbuf, {offset}, {width}) and "); + match &guard.test { + GuardTest::Value { operator, value } => { + let op = lua_compare_op(*operator); + let _ = write!( + out, + "({reader}(tvbuf, {offset}, {width}, {swap}) {op} {value}))" + ); + } + GuardTest::Labels { ranges, .. } => { + if ranges.is_empty() { + out.push_str("false)"); + return; + } + out.push('('); + for (idx, (low, high)) in ranges.iter().enumerate() { + if idx > 0 { + out.push_str(" or "); + } + if low == high { + let _ = write!(out, "({reader}(tvbuf, {offset}, {width}, {swap}) == {low})"); + } else { + let _ = write!( + out, + "({reader}(tvbuf, {offset}, {width}, {swap}) >= {low} and \ + {reader}(tvbuf, {offset}, {width}, {swap}) <= {high})" + ); + } + } + out.push_str("))"); + } + } +} + +const fn lua_compare_op(op: CompareOp) -> &'static str { + match op { + CompareOp::Equal => "==", + CompareOp::NotEqual => "~=", + CompareOp::Less => "<", + CompareOp::LessOrEqual => "<=", + CompareOp::Greater => ">", + CompareOp::GreaterOrEqual => ">=", + } +} + +fn emit_registration(out: &mut String, proto_name: &str, udp_port: Option) { + let _ = writeln!( + out, + "function proto.dissector(tvbuf, pinfo, root)\n \ + pinfo.cols.protocol:set(\"{proto_name}\")\n \ + local subtree = root:add(proto, tvbuf:range(0, tvbuf:len()))\n \ + if not dispatch(tvbuf, pinfo, subtree) then\n \ + pinfo.cols.info:set(\"Unrecognised XTCE packet\")\n \ + end\n\ + end\n" + ); + + let _ = writeln!( + out, + "local wtap_table = DissectorTable.get(\"wtap_encap\")\n\ + if wtap_table and wtap_encaps and wtap_encaps.USER0 then\n \ + wtap_table:add(wtap_encaps.USER0, proto)\n\ + end" + ); + + if let Some(port) = udp_port { + let _ = writeln!( + out, + "\nlocal udp_table = DissectorTable.get(\"udp.port\")\n\ + if udp_table then\n \ + udp_table:add({port}, proto)\n\ + end" + ); + } +} + +fn write_indent(out: &mut String, depth: usize) { + for _ in 0..depth { + out.push_str(" "); + } +} + +fn sanitise_proto_name(name: &str) -> String { + let mut out = String::with_capacity(5 + name.len()); + out.push_str("xtce_"); + for ch in name.chars() { + if ch.is_ascii_alphanumeric() { + out.push(ch.to_ascii_lowercase()); + } else { + out.push('_'); + } + } + out +} + +fn write_lua_quoted(out: &mut String, text: &str) { + out.push('"'); + for ch in text.chars() { + match ch { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + c if c.is_control() => { + let _ = write!(out, "\\{:03}", c as u32); + } + c => out.push(c), + } + } + out.push('"'); +} + +/// Executes `xtce wireshark` using a pre-loaded [`XtceDb`]. +/// +/// # Errors +/// +/// Returns an error if dissector compilation or file output fails. +pub fn run_with_db(db: &XtceDb, options: &Options<'_>) -> Result<(), Box> { + let label = if options.definition.as_os_str() == "-" { + "" + } else { + options.definition.to_str().unwrap_or("") + }; + let lua = generate_lua(db, options.root, label, options.udp_port)?; + + match options.out { + Some(path) if path.as_os_str() != "-" => { + std::fs::write(path, lua)?; + eprintln!("wrote Wireshark dissector to {}", path.display()); + } + _ => print!("{lua}"), + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use xtce_model::XtceDb; + + use super::{generate_lua, write_lua_quoted}; + + const SAMPLE_XTCE: &str = r#" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +"#; + + #[test] + fn generates_lua_dissector_with_proto_fields_and_containers() { + let db = XtceDb::from_xml(SAMPLE_XTCE).expect("valid xml"); + let lua = generate_lua(&db, None, "cubesat.xml", Some(5005)).expect("generates lua"); + + assert!(lua.contains("local proto = Proto(\"xtce_ccsdspacket\", \"CCSDSPacket\")")); + assert!(lua.contains("ProtoField.uint64(\"xtce_ccsdspacket.apid\", \"APID\", base.DEC)")); + assert!(lua.contains("ProtoField.string(\"xtce_ccsdspacket.mode\", \"MODE\")")); + assert!(lua.contains("ProtoField.int64(\"xtce_ccsdspacket.temp\", \"TEMP\", base.DEC)")); + assert!(lua.contains("ProtoField.double(\"xtce_ccsdspacket.temp.eng\", \"TEMP\")")); + assert!(lua.contains("local function dissect_Hkpacket(tvbuf, pinfo, subtree)")); + assert!(lua.contains("(read_bits_uint(tvbuf, 0, 11, false) == 42)")); + assert!(lua.contains("if raw == 0 then label = \"SAFE\"")); + assert!(lua.contains("if raw == 1 then label = \"NOMINAL\"")); + assert!(lua.contains("wtap_table:add(wtap_encaps.USER0, proto)")); + assert!(lua.contains("udp_table:add(5005, proto)")); + } + + #[test] + fn omits_udp_registration_when_port_is_none() { + let db = XtceDb::from_xml(SAMPLE_XTCE).expect("valid xml"); + let lua = generate_lua(&db, None, "cubesat.xml", None).expect("generates lua"); + + assert!(lua.contains("wtap_table:add(wtap_encaps.USER0, proto)")); + assert!(!lua.contains("udp_table:add(")); + } + + #[test] + fn escapes_lua_strings_safely() { + let mut buf = String::new(); + write_lua_quoted(&mut buf, "a\"b\\c\nd"); + assert_eq!(buf, "\"a\\\"b\\\\c\\nd\""); + } +} From 2ce88b7cc8e94e7d92960fc4f1c858cb3f4f80f3 Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Wed, 18 Nov 2026 14:28:49 +0100 Subject: [PATCH 05/13] feat(pus): add no_std ECSS-E-ST-70-41C (PUS-C) crate and HIL OBC responder Add the 'xtce-pus' crate (#![no_std], zero external dependencies, zero heap allocations, no panic paths) implementing ECSS-E-ST-70-41C Packet Utilization Standard (PUS-C) over CCSDS 133.0-B Space Packets: - Compile-time lookup-table CRC-16-CCITT (0x1021, initial 0xFFFF) per ECSS Annex B - Zero-copy PUS-C Telemetry (TM) and Telecommand (TC) secondary headers with CUC 4+2 timestamps and AckFlags - Service codecs for ST[01] Request Verification, ST[03] Housekeeping, ST[05] Event Reporting, and ST[17] Test - Deterministic 'PusResponder' flight state machine for bare-metal OBCs and closed-loop Hardware-in-the-Loop (HIL) testing - CLI 'xtce pus' subcommand for stream inspection and '--hil-demo' closed-loop simulation --- Cargo.lock | 5 + Cargo.toml | 1 + crates/xtce-cli/Cargo.toml | 1 + crates/xtce-cli/src/main.rs | 36 +++ crates/xtce-cli/src/pus.rs | 316 +++++++++++++++++++++ crates/xtce-pus/Cargo.toml | 14 + crates/xtce-pus/README.md | 16 ++ crates/xtce-pus/src/crc.rs | 83 ++++++ crates/xtce-pus/src/hil.rs | 355 ++++++++++++++++++++++++ crates/xtce-pus/src/lib.rs | 194 +++++++++++++ crates/xtce-pus/src/packet.rs | 472 ++++++++++++++++++++++++++++++++ crates/xtce-pus/src/services.rs | 263 ++++++++++++++++++ 12 files changed, 1756 insertions(+) create mode 100644 crates/xtce-cli/src/pus.rs create mode 100644 crates/xtce-pus/Cargo.toml create mode 100644 crates/xtce-pus/README.md create mode 100644 crates/xtce-pus/src/crc.rs create mode 100644 crates/xtce-pus/src/hil.rs create mode 100644 crates/xtce-pus/src/lib.rs create mode 100644 crates/xtce-pus/src/packet.rs create mode 100644 crates/xtce-pus/src/services.rs diff --git a/Cargo.lock b/Cargo.lock index e1dd06f..8185d70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -931,6 +931,7 @@ dependencies = [ "xtce-codegen", "xtce-decode", "xtce-model", + "xtce-pus", ] [[package]] @@ -976,6 +977,10 @@ dependencies = [ "thiserror", ] +[[package]] +name = "xtce-pus" +version = "0.1.1" + [[package]] name = "zerocopy" version = "0.8.56" diff --git a/Cargo.toml b/Cargo.toml index 3f77042..0909f61 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ authors = ["Maciej Myszkiewicz"] xtce-model = { path = "crates/xtce-model", version = "0.1.0" } xtce-decode = { path = "crates/xtce-decode", version = "0.1.0" } xtce-codegen = { path = "crates/xtce-codegen", version = "0.1.0" } +xtce-pus = { path = "crates/xtce-pus", version = "0.1.1" } # Keep this list short and justified — see CONTRIBUTING.md rule 7. anyhow = "1" diff --git a/crates/xtce-cli/Cargo.toml b/crates/xtce-cli/Cargo.toml index 4eb1c3d..135c9f5 100644 --- a/crates/xtce-cli/Cargo.toml +++ b/crates/xtce-cli/Cargo.toml @@ -19,4 +19,5 @@ path = "src/main.rs" xtce-model.workspace = true xtce-decode.workspace = true xtce-codegen.workspace = true +xtce-pus.workspace = true clap.workspace = true diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index 13fb308..f2d2717 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -22,6 +22,7 @@ use xtce_model::XtceDb; mod decode; mod info; mod pcap; +mod pus; mod wireshark; #[derive(Parser)] @@ -133,6 +134,28 @@ enum Command { limit: Option, }, + /// Inspect ECSS-E-ST-70-41C (PUS-C) packet streams or run a closed-loop HIL OBC session. + Pus { + /// File of concatenated CCSDS/PUS packets. Use '-' to read from standard input. + packets: Option, + + /// Run a closed-loop Hardware-in-the-Loop (HIL) session against the no_std OBC responder. + #[arg(long)] + hil_demo: bool, + + /// Write HIL session packets to this raw stream file. + #[arg(long, short)] + out: Option, + + /// Bytes of per-packet wrapper to skip before each CCSDS header. + #[arg(long, default_value_t = 0)] + skip_header_bytes: usize, + + /// Stop after this many packets. + #[arg(long)] + limit: Option, + }, + /// Time loading an XTCE file. Bench { /// XTCE file to load. Use '-' to read from standard input. @@ -219,6 +242,19 @@ fn run(cli: Cli) -> Result<(), Box> { skip_header_bytes, limit, }), + Command::Pus { + packets, + hil_demo, + out, + skip_header_bytes, + limit, + } => pus::run(&pus::Options { + packets: packets.as_deref(), + hil_demo, + out: out.as_deref(), + skip_header_bytes, + limit, + }), Command::Bench { file, iterations } => run_bench(&file, iterations), } } diff --git a/crates/xtce-cli/src/pus.rs b/crates/xtce-cli/src/pus.rs new file mode 100644 index 0000000..6e7dcda --- /dev/null +++ b/crates/xtce-cli/src/pus.rs @@ -0,0 +1,316 @@ +//! `xtce pus` — inspect ECSS-E-ST-70-41C (PUS-C) packet streams and run closed-loop HIL demos. + +use std::io::{Read, Write}; +use std::path::Path; + +use xtce_decode::PacketReader; +use xtce_pus::{ + AckFlags, HousekeepingMessage, MAX_HIL_FRAME_LEN, ObcHousekeeping, PusError, PusHeader, + PusPacket, PusResponder, PusService, TcParams, TestMessage, VerificationReport, encode_tc, +}; + +/// Configuration for `xtce pus`. +pub struct Options<'a> { + pub packets: Option<&'a Path>, + pub hil_demo: bool, + pub out: Option<&'a Path>, + pub skip_header_bytes: usize, + pub limit: Option, +} + +fn open_packet_source(packets: &Path) -> std::io::Result> { + if packets.as_os_str() == "-" { + Ok(Box::new(std::io::BufReader::new(std::io::stdin()))) + } else { + let file = std::fs::File::open(packets)?; + Ok(Box::new(std::io::BufReader::new(file))) + } +} + +/// Executes `xtce pus`. +/// +/// # Errors +/// +/// Returns an error if neither `--hil-demo` nor a packet source path is given, or if I/O fails. +pub fn run(options: &Options<'_>) -> Result<(), Box> { + let stdout = std::io::stdout(); + let mut out = std::io::BufWriter::new(stdout.lock()); + + if options.hil_demo { + run_hil_demo(&mut out, options.out)?; + out.flush()?; + return Ok(()); + } + + let Some(packets_path) = options.packets else { + return Err("provide a packet stream file (or '-') or pass --hil-demo".into()); + }; + + let source = open_packet_source(packets_path)?; + let mut reader = PacketReader::new(source, options.skip_header_bytes); + inspect_stream(&mut reader, &mut out, options.limit)?; + out.flush()?; + Ok(()) +} + +fn inspect_stream( + reader: &mut PacketReader, + out: &mut W, + limit: Option, +) -> Result<(), Box> { + let mut total = 0usize; + let mut valid = 0usize; + let mut crc_failed = 0usize; + let mut malformed = 0usize; + + while let Some(framed) = reader.next_packet()? { + if limit.is_some_and(|max| total >= max) { + break; + } + let index = total; + total += 1; + + match PusPacket::parse(framed.bytes()) { + Ok(pkt) => { + valid += 1; + write_pus_packet(out, index, &pkt)?; + } + Err(PusError::CrcMismatch { expected, computed }) => { + crc_failed += 1; + writeln!( + out, + "packet {index:>4} [CRC FAIL] packet=0x{expected:04X} computed=0x{computed:04X}" + )?; + } + Err(err) => { + malformed += 1; + writeln!(out, "packet {index:>4} [NON-PUS] {err}")?; + } + } + } + + writeln!(out)?; + writeln!( + out, + "{total} packet(s): {valid} valid ECSS PUS (CRC-16-CCITT ok), {crc_failed} CRC failed, {malformed} non-PUS" + )?; + Ok(()) +} + +fn write_pus_packet( + out: &mut impl Write, + index: usize, + pkt: &PusPacket<'_>, +) -> std::io::Result<()> { + match pkt.header { + PusHeader::Telecommand { + version, + service, + subtype, + source_id, + .. + } => { + write!( + out, + "packet {index:>4} TC[{service},{subtype}] PUS-v{version} apid=0x{:03X} seq={} src=0x{source_id:04X} crc=0x{:04X} ", + pkt.apid, pkt.sequence_count, pkt.crc + )?; + } + PusHeader::Telemetry { + version, + service, + subtype, + msg_counter, + timestamp, + .. + } => { + write!( + out, + "packet {index:>4} TM[{service},{subtype}] PUS-v{version} apid=0x{:03X} seq={} cnt={msg_counter} t={}s crc=0x{:04X} ", + pkt.apid, pkt.sequence_count, timestamp.coarse_seconds, pkt.crc + )?; + } + } + + match pkt.decode_service() { + Ok(PusService::Verification(ver)) => write_verification_summary(out, ver), + Ok(PusService::Housekeeping(hk)) => write_hk_summary(out, &hk), + Ok(PusService::Event(ev)) => writeln!( + out, + "Event({:?}, id=0x{:04X}, aux={}B)", + ev.severity, + ev.event_id, + ev.aux_data.len() + ), + Ok(PusService::Test(TestMessage::AreYouAliveCommand)) => { + writeln!(out, "AreYouAliveCommand") + } + Ok(PusService::Test(TestMessage::AreYouAliveReport)) => { + writeln!(out, "AreYouAliveReport") + } + Ok(PusService::Custom { app_data, .. }) => { + writeln!(out, "ApplicationData({}B)", app_data.len()) + } + Err(err) => writeln!(out, "MalformedService({err})"), + } +} + +fn write_verification_summary( + out: &mut impl Write, + ver: VerificationReport, +) -> std::io::Result<()> { + match ver { + VerificationReport::AcceptanceSuccess { request_id } => { + writeln!(out, "AcceptanceSuccess(req=0x{request_id:08X})") + } + VerificationReport::AcceptanceFailure { + request_id, + failure_code, + } => writeln!( + out, + "AcceptanceFailure(req=0x{request_id:08X}, code=0x{failure_code:04X})" + ), + VerificationReport::ExecutionStartSuccess { request_id } => { + writeln!(out, "ExecutionStartSuccess(req=0x{request_id:08X})") + } + VerificationReport::ExecutionCompleteSuccess { request_id } => { + writeln!(out, "ExecutionCompleteSuccess(req=0x{request_id:08X})") + } + VerificationReport::ExecutionCompleteFailure { + request_id, + failure_code, + } => writeln!( + out, + "ExecutionCompleteFailure(req=0x{request_id:08X}, code=0x{failure_code:04X})" + ), + } +} + +fn write_hk_summary(out: &mut impl Write, hk: &HousekeepingMessage<'_>) -> std::io::Result<()> { + match hk { + HousekeepingMessage::EnablePeriodic { sid } => { + writeln!(out, "EnablePeriodicHk(sid={sid})") + } + HousekeepingMessage::DisablePeriodic { sid } => { + writeln!(out, "DisablePeriodicHk(sid={sid})") + } + HousekeepingMessage::OneShotRequest { sid } => { + writeln!(out, "OneShotHkRequest(sid={sid})") + } + HousekeepingMessage::ParameterReport { sid, parameters } => { + if *sid == ObcHousekeeping::SID { + if let Some(obc) = ObcHousekeeping::from_parameter_bytes(parameters) { + return writeln!( + out, + "ObcHkReport(sid={sid}, uptime={}s, vbus={}.{:02}V, temp={}.{:02}C, mode={})", + obc.uptime_s, + obc.bus_voltage_mv / 1_000, + (obc.bus_voltage_mv % 1_000) / 10, + obc.obc_temp_cdeg / 100, + (obc.obc_temp_cdeg.unsigned_abs()) % 100, + obc.mode + ); + } + } + writeln!(out, "HkParameterReport(sid={sid}, {}B)", parameters.len()) + } + } +} + +fn run_hil_demo( + out: &mut impl Write, + capture_out: Option<&Path>, +) -> Result<(), Box> { + writeln!( + out, + "=== ECSS-E-ST-70-41C (PUS-C) Hardware-in-the-Loop (HIL) Closed-Loop Session ===" + )?; + let mut responder = PusResponder::new(0x010, 0x0001); + let mut recorded_stream: Vec = Vec::with_capacity(512); + let mut frame_index = 0usize; + + let sid_bytes = ObcHousekeeping::SID.to_be_bytes(); + let steps: [(u8, u8, &[u8], bool); 4] = [ + (17, 1, &[], false), + (3, 5, &sid_bytes, false), + (3, 27, &sid_bytes, false), + (17, 1, &[], true), + ]; + + let mut tc_buf = [0u8; MAX_HIL_FRAME_LEN]; + let mut tm_frames = [[0u8; MAX_HIL_FRAME_LEN]; 4]; + let mut tm_lens = [0usize; 4]; + + for (seq, &(service, subtype, app_data, inject_bit_flip)) in steps.iter().enumerate() { + responder.tick_second(); + let tc_len = encode_tc( + &TcParams { + apid: 0x010, + sequence_count: u16::try_from(seq).unwrap_or(0), + ack: AckFlags::ACCEPT_AND_COMPLETE, + service, + subtype, + source_id: 0x0042, + }, + app_data, + &mut tc_buf, + )?; + + if inject_bit_flip { + tc_buf[7] ^= 0x80; + } + + if let Ok(parsed_tc) = PusPacket::parse(&tc_buf[..tc_len]) { + write_pus_packet(out, frame_index, &parsed_tc)?; + recorded_stream.extend_from_slice(&tc_buf[..tc_len]); + } else { + writeln!( + out, + "packet {frame_index:>4} [UPLINK SEU BIT-FLIP INJECTED -> CRC-16-CCITT INVALID]" + )?; + } + frame_index += 1; + + let tm_count = + responder.process_telecommand(&tc_buf[..tc_len], &mut tm_frames, &mut tm_lens)?; + for slot in 0..tm_count { + let slice = &tm_frames[slot][..tm_lens[slot]]; + if let Ok(parsed_tm) = PusPacket::parse(slice) { + write_pus_packet(out, frame_index, &parsed_tm)?; + } + recorded_stream.extend_from_slice(slice); + frame_index += 1; + } + } + + if let Some(path) = capture_out { + std::fs::write(path, &recorded_stream)?; + eprintln!( + "wrote {} bytes of ECSS PUS HIL frames to {}", + recorded_stream.len(), + path.display() + ); + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::run_hil_demo; + + #[test] + fn hil_demo_executes_all_four_ecss_pus_scenarios() { + let mut out = Vec::new(); + run_hil_demo(&mut out, None).expect("hil demo succeeds"); + let text = String::from_utf8(out).expect("utf8"); + + assert!(text.contains("TC[17,1]")); + assert!(text.contains("TM[17,2]")); + assert!(text.contains("AcceptanceSuccess")); + assert!(text.contains("EnablePeriodicHk(sid=1)")); + assert!(text.contains("ObcHkReport(sid=1")); + assert!(text.contains("AcceptanceFailure")); + assert!(text.contains("Event(LowAnomaly, id=0x0101")); + } +} diff --git a/crates/xtce-pus/Cargo.toml b/crates/xtce-pus/Cargo.toml new file mode 100644 index 0000000..a2226bf --- /dev/null +++ b/crates/xtce-pus/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "xtce-pus" +description = "ECSS-E-ST-70-41C Packet Utilization Standard (PUS-C) no_std framing, CRC-16-CCITT, and HIL responder" +readme = "README.md" +keywords = ["ecss", "pus", "ccsds", "spacecraft", "no-std"] +categories = ["aerospace::space-protocols", "no-std", "embedded"] +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true + +[dependencies] diff --git a/crates/xtce-pus/README.md b/crates/xtce-pus/README.md new file mode 100644 index 0000000..3f6fb18 --- /dev/null +++ b/crates/xtce-pus/README.md @@ -0,0 +1,16 @@ +# xtce-pus + +`#![no_std]`, zero-allocation implementation of the European Cooperation for Space +Standardization **ECSS-E-ST-70-41C Packet Utilization Standard (PUS-C)** over CCSDS 133.0-B +Space Packets, with a bare-metal Hardware-in-the-Loop (HIL) spacecraft responder. + +## Capabilities + +- **CRC-16-CCITT (`0x1021`, initial `0xFFFF`)** per ECSS-E-ST-70-41C Annex B (compile-time lookup table, zero branches). +- **PUS-C Telemetry (`TM`) and Telecommand (`TC`) secondary headers**, including CUC (4+2 octet) spacecraft time and telecommand acknowledgement flags. +- **Core ECSS PUS Services**: + - **ST\[01\] Request Verification**: `TM[1,1]` Acceptance Success, `TM[1,2]` Acceptance Failure, `TM[1,7]` Execution Complete Success, `TM[1,8]` Execution Complete Failure. + - **ST\[03\] Housekeeping**: `TC[3,5]` Enable HK, `TC[3,6]` Disable HK, `TC[3,27]` One-Shot HK Request, `TM[3,25]` Housekeeping Parameter Report. + - **ST\[05\] Event Reporting**: `TM[5,1]` Informative Event through `TM[5,4]` High-Severity Anomaly. + - **ST\[17\] Test Service**: `TC[17,1]` Are-You-Alive Connection Test and `TM[17,2]` Are-You-Alive Connection Report. +- **`PusResponder` HIL State Machine**: zero-heap flight responder suitable for `thumbv7em-none-eabihf` (STM32), RISC-V (ESP32), or desktop HIL benches. diff --git a/crates/xtce-pus/src/crc.rs b/crates/xtce-pus/src/crc.rs new file mode 100644 index 0000000..4cb3ac2 --- /dev/null +++ b/crates/xtce-pus/src/crc.rs @@ -0,0 +1,83 @@ +//! ECSS-E-ST-70-41C Annex B / CCSDS 131.0-B CRC-16-CCITT packet error control. +//! +//! Generator polynomial: $G(x) = x^{16} + x^{12} + x^5 + 1$ (`0x1021`), initial syndrome +//! `0xFFFF`, no input reflection, no final XOR. Over the ASCII string `"123456789"` this +//! produces `0x29B1`, and computing the syndrome over a frame followed by its two big-endian +//! CRC octets yields `0x0000`. + +const POLY: u16 = 0x1021; + +const fn build_table() -> [u16; 256] { + let mut table = [0u16; 256]; + let mut i = 0usize; + while i < 256 { + let mut crc = (i as u16) << 8; + let mut bit = 0; + while bit < 8 { + if (crc & 0x8000) != 0 { + crc = (crc << 1) ^ POLY; + } else { + crc <<= 1; + } + bit += 1; + } + table[i] = crc; + i += 1; + } + table +} + +/// Precomputed 256-entry lookup table for CRC-16-CCITT (`0x1021`). +const TABLE: [u16; 256] = build_table(); + +/// Computes the 16-bit ECSS PUS Packet Error Control (CRC-16-CCITT) over `bytes`. +#[must_use] +pub const fn crc16_ccitt(bytes: &[u8]) -> u16 { + let mut crc: u16 = 0xFFFF; + let mut idx = 0usize; + while idx < bytes.len() { + let lookup = ((crc >> 8) as u8) ^ bytes[idx]; + crc = (crc << 8) ^ TABLE[lookup as usize]; + idx += 1; + } + crc +} + +/// Returns `true` if `frame` ends with a valid 2-byte big-endian CRC-16-CCITT syndrome. +#[must_use] +pub const fn verify_crc16_ccitt(frame: &[u8]) -> bool { + if frame.len() < 2 { + return false; + } + crc16_ccitt(frame) == 0 +} + +#[cfg(test)] +mod tests { + use super::{crc16_ccitt, verify_crc16_ccitt}; + + #[test] + fn matches_ecss_annex_b_standard_check_value() { + assert_eq!(crc16_ccitt(b""), 0xFFFF); + assert_eq!(crc16_ccitt(b"123456789"), 0x29B1); + } + + #[test] + fn appended_big_endian_syndrome_verifies_to_zero_residue() { + let mut frame = [b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', 0, 0]; + let crc = crc16_ccitt(&frame[..9]); + let [hi, lo] = crc.to_be_bytes(); + frame[9] = hi; + frame[10] = lo; + + assert!(verify_crc16_ccitt(&frame)); + frame[4] ^= 0x01; + assert!(!verify_crc16_ccitt(&frame)); + } + + #[test] + fn rejects_frames_shorter_than_two_bytes() { + assert!(!verify_crc16_ccitt(&[])); + assert!(!verify_crc16_ccitt(&[0xFF])); + } +} diff --git a/crates/xtce-pus/src/hil.rs b/crates/xtce-pus/src/hil.rs new file mode 100644 index 0000000..34cc9cc --- /dev/null +++ b/crates/xtce-pus/src/hil.rs @@ -0,0 +1,355 @@ +//! `#![no_std]` Hardware-in-the-Loop (HIL) On-Board Computer (OBC) ECSS PUS responder. +//! +//! `PusResponder` implements a deterministic, zero-allocation spacecraft command and telemetry +//! handler suitable for flashing onto an STM32 (`thumbv7em-none-eabihf`), RP2040/RP2350, or +//! ESP32 microcontroller connected over UART/CAN/UDP, as well as running in closed-loop +//! desktop integration tests. + +use crate::packet::{CucTimestamp, PusError, PusHeader, PusPacket, TmParams, encode_tm}; +use crate::services::ObcHousekeeping; + +///Maximum byte size of a single response frame emitted by [`PusResponder`]. +pub const MAX_HIL_FRAME_LEN: usize = 64; + +/// Failure code reported in `TM[1,2]` when a telecommand fails CRC-16-CCITT verification. +pub const ERR_CODE_CRC_MISMATCH: u16 = 0xBAD0; + +/// Failure code reported in `TM[1,2]` when a frame is not a telecommand. +pub const ERR_CODE_NOT_A_TC: u16 = 0xBAD1; + +/// Failure code reported in `TM[1,8]` when a service, subtype, or `SID` is unsupported. +pub const ERR_CODE_UNSUPPORTED: u16 = 0x0404; + +/// Event ID emitted in `TM[5,2]` when a corrupted telecommand is rejected. +pub const EVENT_ID_CORRUPTED_TC: u16 = 0x0101; + +/// Event ID emitted in `TM[5,1]` when periodic housekeeping is enabled. +pub const EVENT_ID_HK_ENABLED: u16 = 0x0305; + +/// Deterministic, zero-heap ECSS PUS spacecraft responder state machine. +#[derive(Clone, Debug)] +pub struct PusResponder { + /// 11-bit CCSDS Application Process ID for emitted telemetry. + pub apid: u16, + /// Ground destination ID written into PUS-C telemetry secondary headers. + pub destination_id: u16, + /// 14-bit monotonic CCSDS sequence counter. + pub tm_seq_count: u16, + /// 16-bit monotonic PUS message counter. + pub msg_counter: u16, + /// Current on-board housekeeping values. + pub hk: ObcHousekeeping, + /// Whether periodic `TM[3,25]` housekeeping generation is enabled. + pub periodic_hk_enabled: bool, +} + +impl PusResponder { + /// Creates a new responder in `NOMINAL` mode (`mode = 2`, 28.20 V bus, 22.50 °C OBC). + #[must_use] + pub const fn new(apid: u16, destination_id: u16) -> Self { + Self { + apid: apid & 0x07FF, + destination_id, + tm_seq_count: 0, + msg_counter: 0, + hk: ObcHousekeeping { + uptime_s: 1, + bus_voltage_mv: 28_200, + obc_temp_cdeg: 2_250, + mode: 2, + }, + periodic_hk_enabled: false, + } + } + + /// Advances on-board time by 1 second and updates simulated bus voltage and temperature. + pub const fn tick_second(&mut self) { + self.hk.uptime_s = self.hk.uptime_s.wrapping_add(1); + let phase = (self.hk.uptime_s % 8) as i16; + self.hk.bus_voltage_mv = 28_150 + (phase as u16) * 15; + self.hk.obc_temp_cdeg = 2_240 + (phase - 4) * 5; + } + + /// Processes one incoming telecommand frame and writes the resulting telemetry response + /// frames into `out_frames[..count]` with their byte lengths in `out_lens[..count]`. + /// + /// Returns the number of telemetry frames emitted. + /// + /// # Errors + /// + /// Returns [`PusError`] only if `out_frames` / `out_lens` lack capacity for the response + /// packets or if a frame is shorter than the 4-byte CCSDS request identifier. + pub fn process_telecommand( + &mut self, + tc_frame: &[u8], + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + ) -> Result { + let max_slots = out_frames.len().min(out_lens.len()); + let mut count = 0usize; + + let packet = match PusPacket::parse(tc_frame) { + Ok(pkt) => pkt, + Err(PusError::CrcMismatch { expected, .. }) if tc_frame.len() >= 4 => { + let req_id = + u32::from_be_bytes([tc_frame[0], tc_frame[1], tc_frame[2], tc_frame[3]]); + self.push_tm_1_2( + req_id, + ERR_CODE_CRC_MISMATCH, + out_frames, + out_lens, + &mut count, + max_slots, + )?; + let aux = expected.to_be_bytes(); + self.push_event( + 2, + EVENT_ID_CORRUPTED_TC, + &aux, + out_frames, + out_lens, + &mut count, + max_slots, + )?; + return Ok(count); + } + Err(err) => return Err(err), + }; + + let PusHeader::Telecommand { + ack, + service, + subtype, + .. + } = packet.header + else { + self.push_tm_1_2( + packet.request_id, + ERR_CODE_NOT_A_TC, + out_frames, + out_lens, + &mut count, + max_slots, + )?; + return Ok(count); + }; + + if ack.acceptance { + self.push_tm_1_1( + packet.request_id, + out_frames, + out_lens, + &mut count, + max_slots, + )?; + } + + let exec_ok = self.execute_service( + service, + subtype, + packet.app_data, + out_frames, + out_lens, + &mut count, + max_slots, + )?; + + if exec_ok { + if ack.completion { + self.push_tm_1_7( + packet.request_id, + out_frames, + out_lens, + &mut count, + max_slots, + )?; + } + } else { + self.push_tm_1_8( + packet.request_id, + ERR_CODE_UNSUPPORTED, + out_frames, + out_lens, + &mut count, + max_slots, + )?; + } + + Ok(count) + } + + #[allow(clippy::too_many_arguments)] + fn execute_service( + &mut self, + service: u8, + subtype: u8, + app_data: &[u8], + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result { + match (service, subtype) { + (17, 1) => { + self.emit_frame(17, 2, &[], out_frames, out_lens, count, max_slots)?; + Ok(true) + } + (3, 27) if app_data.len() >= 2 => { + let sid = u16::from_be_bytes([app_data[0], app_data[1]]); + if sid != ObcHousekeeping::SID { + return Ok(false); + } + let payload = self.hk.to_app_data(); + self.emit_frame(3, 25, &payload, out_frames, out_lens, count, max_slots)?; + Ok(true) + } + (3, 5) if app_data.len() >= 2 => { + let sid = u16::from_be_bytes([app_data[0], app_data[1]]); + if sid != ObcHousekeeping::SID { + return Ok(false); + } + self.periodic_hk_enabled = true; + self.push_event( + 1, + EVENT_ID_HK_ENABLED, + &app_data[..2], + out_frames, + out_lens, + count, + max_slots, + )?; + Ok(true) + } + (3, 6) if app_data.len() >= 2 => { + let sid = u16::from_be_bytes([app_data[0], app_data[1]]); + if sid != ObcHousekeeping::SID { + return Ok(false); + } + self.periodic_hk_enabled = false; + Ok(true) + } + _ => Ok(false), + } + } + + fn push_tm_1_1( + &mut self, + request_id: u32, + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result<(), PusError> { + let payload = request_id.to_be_bytes(); + self.emit_frame(1, 1, &payload, out_frames, out_lens, count, max_slots) + } + + fn push_tm_1_2( + &mut self, + request_id: u32, + failure_code: u16, + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result<(), PusError> { + let r = request_id.to_be_bytes(); + let c = failure_code.to_be_bytes(); + let payload = [r[0], r[1], r[2], r[3], c[0], c[1]]; + self.emit_frame(1, 2, &payload, out_frames, out_lens, count, max_slots) + } + + fn push_tm_1_7( + &mut self, + request_id: u32, + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result<(), PusError> { + let payload = request_id.to_be_bytes(); + self.emit_frame(1, 7, &payload, out_frames, out_lens, count, max_slots) + } + + fn push_tm_1_8( + &mut self, + request_id: u32, + failure_code: u16, + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result<(), PusError> { + let r = request_id.to_be_bytes(); + let c = failure_code.to_be_bytes(); + let payload = [r[0], r[1], r[2], r[3], c[0], c[1]]; + self.emit_frame(1, 8, &payload, out_frames, out_lens, count, max_slots) + } + + #[allow(clippy::too_many_arguments)] + fn push_event( + &mut self, + subtype: u8, + event_id: u16, + aux: &[u8], + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result<(), PusError> { + let mut buf = [0u8; 16]; + let id = event_id.to_be_bytes(); + buf[0] = id[0]; + buf[1] = id[1]; + let copy_len = aux.len().min(buf.len() - 2); + buf[2..2 + copy_len].copy_from_slice(&aux[..copy_len]); + self.emit_frame( + 5, + subtype, + &buf[..2 + copy_len], + out_frames, + out_lens, + count, + max_slots, + ) + } + + #[allow(clippy::too_many_arguments)] + fn emit_frame( + &mut self, + service: u8, + subtype: u8, + app_data: &[u8], + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result<(), PusError> { + if *count >= max_slots { + return Err(PusError::BufferTooSmall { + required: *count + 1, + available: max_slots, + }); + } + + let params = TmParams { + apid: self.apid, + sequence_count: self.tm_seq_count, + service, + subtype, + msg_counter: self.msg_counter, + destination_id: self.destination_id, + timestamp: CucTimestamp { + coarse_seconds: self.hk.uptime_s, + fine_subseconds: 0, + }, + }; + + let len = encode_tm(¶ms, app_data, &mut out_frames[*count])?; + out_lens[*count] = len; + *count += 1; + self.tm_seq_count = (self.tm_seq_count + 1) & 0x3FFF; + self.msg_counter = self.msg_counter.wrapping_add(1); + Ok(()) + } +} diff --git a/crates/xtce-pus/src/lib.rs b/crates/xtce-pus/src/lib.rs new file mode 100644 index 0000000..5fd0746 --- /dev/null +++ b/crates/xtce-pus/src/lib.rs @@ -0,0 +1,194 @@ +//! `#![no_std]` implementation of ECSS-E-ST-70-41C Packet Utilization Standard (PUS-C) +//! over CCSDS 133.0-B Space Packets, with a deterministic Hardware-in-the-Loop (HIL) +//! On-Board Computer responder. +//! +//! # Guarantees +//! +//! * **`#![no_std]` and zero heap allocations.** Every parser, encoder, and HIL responder +//! method operates on caller-supplied byte slices so the crate can run unmodified on bare-metal +//! flight targets (`thumbv7em-none-eabihf` Cortex-M, RISC-V, LEON/SPARC) and ground tools. +//! * **No panics.** `unwrap`, `expect`, and `panic!` are denied across the library. +//! * **End-to-end CRC-16-CCITT protection.** Every parsed and encoded frame is checked or +//! stamped with the ECSS-E-ST-70-41C Annex B syndrome (`0x1021`, initial `0xFFFF`). + +#![no_std] +#![deny(missing_docs)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#![deny(clippy::todo, clippy::unimplemented)] +#![warn(clippy::pedantic)] +#![allow(clippy::module_name_repetitions)] +#![allow( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_sign_loss +)] +#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] + +pub mod crc; +pub mod hil; +pub mod packet; +pub mod services; + +pub use crc::{crc16_ccitt, verify_crc16_ccitt}; +pub use hil::{ + ERR_CODE_CRC_MISMATCH, ERR_CODE_NOT_A_TC, ERR_CODE_UNSUPPORTED, EVENT_ID_CORRUPTED_TC, + EVENT_ID_HK_ENABLED, MAX_HIL_FRAME_LEN, PusResponder, +}; +pub use packet::{ + AckFlags, CucTimestamp, PEC_LEN, PRIMARY_HEADER_LEN, PUS_VERSION_C, PusError, PusHeader, + PusPacket, TC_SECONDARY_HEADER_LEN, TM_SECONDARY_HEADER_LEN, TcParams, TmParams, encode_tc, + encode_tm, +}; +pub use services::{ + EventReport, EventSeverity, HousekeepingMessage, ObcHousekeeping, PusService, TestMessage, + VerificationReport, +}; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hil_responder_handles_st17_are_you_alive_closed_loop() { + let mut responder = PusResponder::new(0x010, 0x0001); + let mut tc_buf = [0u8; 32]; + let tc_len = encode_tc( + &TcParams { + apid: 0x010, + sequence_count: 7, + ack: AckFlags::ACCEPT_AND_COMPLETE, + service: 17, + subtype: 1, + source_id: 0x0042, + }, + &[], + &mut tc_buf, + ) + .expect("encodes TC[17,1]"); + + let parsed_tc = PusPacket::parse(&tc_buf[..tc_len]).expect("valid TC"); + assert_eq!( + parsed_tc.decode_service().expect("service"), + PusService::Test(TestMessage::AreYouAliveCommand) + ); + + let mut out_frames = [[0u8; MAX_HIL_FRAME_LEN]; 4]; + let mut out_lens = [0usize; 4]; + let count = responder + .process_telecommand(&tc_buf[..tc_len], &mut out_frames, &mut out_lens) + .expect("HIL processes TC[17,1]"); + assert_eq!(count, 3); + + // 1. TM[1,1] Acceptance Success + let tm0 = PusPacket::parse(&out_frames[0][..out_lens[0]]).expect("TM[1,1]"); + assert_eq!( + tm0.decode_service().expect("ST[01]"), + PusService::Verification(VerificationReport::AcceptanceSuccess { + request_id: parsed_tc.request_id, + }) + ); + + // 2. TM[17,2] Are-You-Alive Connection Test Report + let tm1 = PusPacket::parse(&out_frames[1][..out_lens[1]]).expect("TM[17,2]"); + assert_eq!( + tm1.decode_service().expect("ST[17]"), + PusService::Test(TestMessage::AreYouAliveReport) + ); + + // 3. TM[1,7] Execution Complete Success + let tm2 = PusPacket::parse(&out_frames[2][..out_lens[2]]).expect("TM[1,7]"); + assert_eq!( + tm2.decode_service().expect("ST[01]"), + PusService::Verification(VerificationReport::ExecutionCompleteSuccess { + request_id: parsed_tc.request_id, + }) + ); + } + + #[test] + fn hil_responder_emits_housekeeping_report_on_st03_one_shot() { + let mut responder = PusResponder::new(0x010, 0x0001); + responder.tick_second(); + + let mut tc_buf = [0u8; 32]; + let sid_bytes = ObcHousekeeping::SID.to_be_bytes(); + let tc_len = encode_tc( + &TcParams { + apid: 0x010, + sequence_count: 8, + ack: AckFlags::ACCEPT_AND_COMPLETE, + service: 3, + subtype: 27, + source_id: 0x0042, + }, + &sid_bytes, + &mut tc_buf, + ) + .expect("encodes TC[3,27]"); + + let mut out_frames = [[0u8; MAX_HIL_FRAME_LEN]; 4]; + let mut out_lens = [0usize; 4]; + let count = responder + .process_telecommand(&tc_buf[..tc_len], &mut out_frames, &mut out_lens) + .expect("HIL processes TC[3,27]"); + assert_eq!(count, 3); + + let hk_pkt = PusPacket::parse(&out_frames[1][..out_lens[1]]).expect("TM[3,25]"); + let PusService::Housekeeping(HousekeepingMessage::ParameterReport { sid, parameters }) = + hk_pkt.decode_service().expect("decodes ST[03]") + else { + panic!("expected TM[3,25] ParameterReport"); + }; + assert_eq!(sid, ObcHousekeeping::SID); + let decoded_hk = ObcHousekeeping::from_parameter_bytes(parameters).expect("OBC HK"); + assert_eq!(decoded_hk, responder.hk); + } + + #[test] + fn hil_responder_rejects_corrupted_crc_with_tm_1_2_and_tm_5_2() { + let mut responder = PusResponder::new(0x010, 0x0001); + let mut tc_buf = [0u8; 32]; + let tc_len = encode_tc( + &TcParams { + apid: 0x010, + sequence_count: 9, + ack: AckFlags::ACCEPT_AND_COMPLETE, + service: 17, + subtype: 1, + source_id: 0x0042, + }, + &[], + &mut tc_buf, + ) + .expect("encodes TC"); + + // Flip one bit in the service byte to corrupt the frame over the link + tc_buf[7] ^= 0x80; + + let mut out_frames = [[0u8; MAX_HIL_FRAME_LEN]; 4]; + let mut out_lens = [0usize; 4]; + let count = responder + .process_telecommand(&tc_buf[..tc_len], &mut out_frames, &mut out_lens) + .expect("HIL handles corrupted TC gracefully"); + assert_eq!(count, 2); + + let tm0 = PusPacket::parse(&out_frames[0][..out_lens[0]]).expect("TM[1,2]"); + assert!(matches!( + tm0.decode_service().expect("ST[01]"), + PusService::Verification(VerificationReport::AcceptanceFailure { + failure_code: ERR_CODE_CRC_MISMATCH, + .. + }) + )); + + let tm1 = PusPacket::parse(&out_frames[1][..out_lens[1]]).expect("TM[5,2]"); + assert!(matches!( + tm1.decode_service().expect("ST[05]"), + PusService::Event(EventReport { + severity: EventSeverity::LowAnomaly, + event_id: EVENT_ID_CORRUPTED_TC, + .. + }) + )); + } +} diff --git a/crates/xtce-pus/src/packet.rs b/crates/xtce-pus/src/packet.rs new file mode 100644 index 0000000..c023f17 --- /dev/null +++ b/crates/xtce-pus/src/packet.rs @@ -0,0 +1,472 @@ +//! Zero-copy ECSS-E-ST-70-41C (PUS-C) packet parsing and encoding over CCSDS 133.0-B. + +use core::fmt; + +use crate::crc::crc16_ccitt; + +/// Size of the CCSDS 133.0-B Primary Header in octets. +pub const PRIMARY_HEADER_LEN: usize = 6; + +/// Size of the PUS-C Telemetry Secondary Header (with 4+2 CUC timestamp) in octets. +pub const TM_SECONDARY_HEADER_LEN: usize = 13; + +/// Size of the PUS-C Telecommand Secondary Header in octets. +pub const TC_SECONDARY_HEADER_LEN: usize = 5; + +/// Size of the trailing Packet Error Control (CRC-16-CCITT) field in octets. +pub const PEC_LEN: usize = 2; + +/// ECSS PUS version number for ECSS-E-ST-70-41C (PUS-C). +pub const PUS_VERSION_C: u8 = 2; + +/// Errors returned while decoding or encoding an ECSS PUS packet. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum PusError { + /// The frame is shorter than the minimum header + CRC size. + ShortPacket { + /// Bytes provided by the caller. + actual: usize, + /// Minimum bytes required for this frame type. + minimum: usize, + }, + /// The CCSDS primary header length field disagrees with the slice length. + LengthMismatch { + /// Total frame length declared by the CCSDS primary header (`6 + C + 1`). + declared: usize, + /// Actual slice length. + actual: usize, + }, + /// The CCSDS Secondary Header Flag (bit 4) is 0; ECSS PUS requires a secondary header. + MissingSecondaryHeader, + /// Unknown or unsupported ECSS PUS version nibble. + UnsupportedPusVersion(u8), + /// Trailing 16-bit CRC-16-CCITT does not match the computed syndrome. + CrcMismatch { + /// 16-bit CRC read from the last two octets of the packet. + expected: u16, + /// 16-bit CRC computed over the preceding octets. + computed: u16, + }, + /// The output slice passed to an encoder is too small to hold the frame. + BufferTooSmall { + /// Bytes needed to encode the packet. + required: usize, + /// Bytes available in the caller's slice. + available: usize, + }, + /// Service-specific application data is shorter than required or invalid. + MalformedServiceData { + /// ECSS service type (`ST[x]`). + service: u8, + /// ECSS message subtype (`TM/TC[x,y]`). + subtype: u8, + }, +} + +impl fmt::Display for PusError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ShortPacket { actual, minimum } => { + write!( + f, + "packet of {actual} byte(s) is shorter than minimum {minimum}" + ) + } + Self::LengthMismatch { declared, actual } => { + write!( + f, + "CCSDS header declares {declared} byte(s) but frame has {actual}" + ) + } + Self::MissingSecondaryHeader => { + write!( + f, + "CCSDS secondary header flag is 0 (required for ECSS PUS)" + ) + } + Self::UnsupportedPusVersion(ver) => { + write!(f, "unsupported ECSS PUS version {ver} (expected 1 or 2)") + } + Self::CrcMismatch { expected, computed } => { + write!( + f, + "CRC-16-CCITT mismatch: packet carries 0x{expected:04X}, computed 0x{computed:04X}" + ) + } + Self::BufferTooSmall { + required, + available, + } => { + write!( + f, + "output buffer of {available} byte(s) cannot hold {required}-byte PUS frame" + ) + } + Self::MalformedServiceData { service, subtype } => { + write!(f, "malformed application data for PUS[{service},{subtype}]") + } + } + } +} + +impl core::error::Error for PusError {} + +/// Telecommand acknowledgement flags in the PUS-C TC secondary header (`ST[01]` stages). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[allow(clippy::struct_excessive_bools)] +pub struct AckFlags { + /// Emit `TM[1,1]` / `TM[1,2]` upon telecommand acceptance check. + pub acceptance: bool, + /// Emit `TM[1,3]` / `TM[1,4]` upon start of execution. + pub start: bool, + /// Emit `TM[1,5]` / `TM[1,6]` during execution progress. + pub progress: bool, + /// Emit `TM[1,7]` / `TM[1,8]` upon execution completion. + pub completion: bool, +} + +impl AckFlags { + /// Requests both acceptance (`TM[1,1]`) and completion (`TM[1,7]`) verification reports. + pub const ACCEPT_AND_COMPLETE: Self = Self { + acceptance: true, + start: false, + progress: false, + completion: true, + }; + + /// Decodes the 4-bit acknowledgement nibble from the first octet of a TC secondary header. + #[must_use] + pub const fn from_nibble(nibble: u8) -> Self { + Self { + acceptance: (nibble & 0b0001) != 0, + start: (nibble & 0b0010) != 0, + progress: (nibble & 0b0100) != 0, + completion: (nibble & 0b1000) != 0, + } + } + + /// Encodes the flags into the lower 4 bits of an octet. + #[must_use] + pub const fn to_nibble(self) -> u8 { + (self.acceptance as u8) + | ((self.start as u8) << 1) + | ((self.progress as u8) << 2) + | ((self.completion as u8) << 3) + } +} + +/// CCSDS Unsegmented Time Code (CUC 4+2: 32-bit coarse seconds, 16-bit fine sub-seconds). +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +pub struct CucTimestamp { + /// Whole seconds since mission epoch. + pub coarse_seconds: u32, + /// Sub-second fraction in units of $2^{-16}$ seconds ($\approx 15.26\ \mu\text{s}$). + pub fine_subseconds: u16, +} + +/// Decoded ECSS PUS secondary header. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum PusHeader { + /// Telemetry secondary header (`Packet Type = 0`). + Telemetry { + /// PUS version number (`1` for PUS-A, `2` for PUS-C). + version: u8, + /// Spacecraft time reference status (4 bits). + time_ref_status: u8, + /// ECSS service type (`ST[x]`). + service: u8, + /// ECSS message subtype (`TM[x,y]`). + subtype: u8, + /// Monotonic per-type message counter. + msg_counter: u16, + /// Ground destination identifier. + destination_id: u16, + /// On-board CUC generation timestamp. + timestamp: CucTimestamp, + }, + /// Telecommand secondary header (`Packet Type = 1`). + Telecommand { + /// PUS version number (`1` for PUS-A, `2` for PUS-C). + version: u8, + /// Requested `ST[01]` verification stages. + ack: AckFlags, + /// ECSS service type (`ST[x]`). + service: u8, + /// ECSS message subtype (`TC[x,y]`). + subtype: u8, + /// Ground source identifier. + source_id: u16, + }, +} + +impl PusHeader { + /// The ECSS service type (`ST[x]`). + #[must_use] + pub const fn service(&self) -> u8 { + match *self { + Self::Telemetry { service, .. } | Self::Telecommand { service, .. } => service, + } + } + + /// The ECSS message subtype (`TM/TC[x,y]`). + #[must_use] + pub const fn subtype(&self) -> u8 { + match *self { + Self::Telemetry { subtype, .. } | Self::Telecommand { subtype, .. } => subtype, + } + } + + /// Returns `true` if this is a telecommand (`TC`), `false` if telemetry (`TM`). + #[must_use] + pub const fn is_telecommand(&self) -> bool { + matches!(self, Self::Telecommand { .. }) + } +} + +/// A validated, zero-copy view of a CCSDS + ECSS PUS packet. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct PusPacket<'a> { + /// 11-bit CCSDS Application Process Identifier. + pub apid: u16, + /// 14-bit CCSDS Packet Sequence Count. + pub sequence_count: u16, + /// First 32 bits of the CCSDS primary header (`Packet ID || Packet Sequence Control`), + /// used by `ST[01]` Request Verification reports to identify a telecommand. + pub request_id: u32, + /// Decoded PUS secondary header. + pub header: PusHeader, + /// Service-specific application data slice (between the secondary header and the 2-byte CRC). + pub app_data: &'a [u8], + /// Verified 16-bit CRC-16-CCITT carried in the final two octets. + pub crc: u16, +} + +impl<'a> PusPacket<'a> { + /// Parses and validates a complete CCSDS + ECSS PUS frame, including its trailing CRC-16-CCITT. + /// + /// # Errors + /// + /// Returns [`PusError`] if the frame is truncated, lacks a secondary header, carries an + /// unknown PUS version, or fails CRC-16-CCITT verification. + pub fn parse(bytes: &'a [u8]) -> Result { + let min_base = PRIMARY_HEADER_LEN + TC_SECONDARY_HEADER_LEN + PEC_LEN; + if bytes.len() < min_base { + return Err(PusError::ShortPacket { + actual: bytes.len(), + minimum: min_base, + }); + } + + let word0 = u16::from_be_bytes([bytes[0], bytes[1]]); + let word1 = u16::from_be_bytes([bytes[2], bytes[3]]); + let data_len = u16::from_be_bytes([bytes[4], bytes[5]]); + let declared_total = PRIMARY_HEADER_LEN + usize::from(data_len) + 1; + + if declared_total != bytes.len() { + return Err(PusError::LengthMismatch { + declared: declared_total, + actual: bytes.len(), + }); + } + + let sec_hdr_flag = ((word0 >> 11) & 0x01) != 0; + if !sec_hdr_flag { + return Err(PusError::MissingSecondaryHeader); + } + + let is_tc = ((word0 >> 12) & 0x01) != 0; + let apid = word0 & 0x07FF; + let sequence_count = word1 & 0x3FFF; + let request_id = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); + + let body_end = bytes.len() - PEC_LEN; + let expected_crc = u16::from_be_bytes([bytes[body_end], bytes[body_end + 1]]); + let computed_crc = crc16_ccitt(&bytes[..body_end]); + if expected_crc != computed_crc { + return Err(PusError::CrcMismatch { + expected: expected_crc, + computed: computed_crc, + }); + } + + let sec = &bytes[PRIMARY_HEADER_LEN..body_end]; + let version = sec[0] >> 4; + if version != 1 && version != PUS_VERSION_C { + return Err(PusError::UnsupportedPusVersion(version)); + } + + if is_tc { + let ack = AckFlags::from_nibble(sec[0] & 0x0F); + let service = sec[1]; + let subtype = sec[2]; + let source_id = u16::from_be_bytes([sec[3], sec[4]]); + let app_data = &sec[TC_SECONDARY_HEADER_LEN..]; + + Ok(Self { + apid, + sequence_count, + request_id, + header: PusHeader::Telecommand { + version, + ack, + service, + subtype, + source_id, + }, + app_data, + crc: expected_crc, + }) + } else { + let min_tm = PRIMARY_HEADER_LEN + TM_SECONDARY_HEADER_LEN + PEC_LEN; + if bytes.len() < min_tm { + return Err(PusError::ShortPacket { + actual: bytes.len(), + minimum: min_tm, + }); + } + let time_ref_status = sec[0] & 0x0F; + let service = sec[1]; + let subtype = sec[2]; + let msg_counter = u16::from_be_bytes([sec[3], sec[4]]); + let destination_id = u16::from_be_bytes([sec[5], sec[6]]); + let coarse_seconds = u32::from_be_bytes([sec[7], sec[8], sec[9], sec[10]]); + let fine_subseconds = u16::from_be_bytes([sec[11], sec[12]]); + let app_data = &sec[TM_SECONDARY_HEADER_LEN..]; + + Ok(Self { + apid, + sequence_count, + request_id, + header: PusHeader::Telemetry { + version, + time_ref_status, + service, + subtype, + msg_counter, + destination_id, + timestamp: CucTimestamp { + coarse_seconds, + fine_subseconds, + }, + }, + app_data, + crc: expected_crc, + }) + } + } +} + +/// Parameters for encoding a PUS-C Telemetry (`TM`) packet. +#[derive(Clone, Copy, Debug)] +pub struct TmParams { + /// 11-bit CCSDS APID. + pub apid: u16, + /// 14-bit CCSDS sequence counter. + pub sequence_count: u16, + /// ECSS service type (`ST[x]`). + pub service: u8, + /// ECSS message subtype (`TM[x,y]`). + pub subtype: u8, + /// Per-type message counter. + pub msg_counter: u16, + /// Ground destination identifier. + pub destination_id: u16, + /// Spacecraft CUC timestamp. + pub timestamp: CucTimestamp, +} + +/// Encodes a complete PUS-C Telemetry (`TM`) frame with trailing CRC-16-CCITT into `out`. +/// +/// Returns the total number of bytes written. +/// +/// # Errors +/// +/// Returns [`PusError::BufferTooSmall`] if `out` cannot hold `21 + app_data.len()` bytes. +pub fn encode_tm(params: &TmParams, app_data: &[u8], out: &mut [u8]) -> Result { + let total = PRIMARY_HEADER_LEN + TM_SECONDARY_HEADER_LEN + app_data.len() + PEC_LEN; + if out.len() < total { + return Err(PusError::BufferTooSmall { + required: total, + available: out.len(), + }); + } + + let word0: u16 = 0x0800 | (params.apid & 0x07FF); // TM (type 0), sec_hdr=1 + let word1: u16 = 0xC000 | (params.sequence_count & 0x3FFF); // unsegmented (3) + let data_len = (total - PRIMARY_HEADER_LEN - 1) as u16; + + out[0..2].copy_from_slice(&word0.to_be_bytes()); + out[2..4].copy_from_slice(&word1.to_be_bytes()); + out[4..6].copy_from_slice(&data_len.to_be_bytes()); + + out[6] = PUS_VERSION_C << 4; + out[7] = params.service; + out[8] = params.subtype; + out[9..11].copy_from_slice(¶ms.msg_counter.to_be_bytes()); + out[11..13].copy_from_slice(¶ms.destination_id.to_be_bytes()); + out[13..17].copy_from_slice(¶ms.timestamp.coarse_seconds.to_be_bytes()); + out[17..19].copy_from_slice(¶ms.timestamp.fine_subseconds.to_be_bytes()); + + let app_end = 19 + app_data.len(); + out[19..app_end].copy_from_slice(app_data); + + let crc = crc16_ccitt(&out[..app_end]); + out[app_end..app_end + 2].copy_from_slice(&crc.to_be_bytes()); + + Ok(total) +} + +/// Parameters for encoding a PUS-C Telecommand (`TC`) packet. +#[derive(Clone, Copy, Debug)] +pub struct TcParams { + /// 11-bit CCSDS APID. + pub apid: u16, + /// 14-bit CCSDS sequence counter. + pub sequence_count: u16, + /// Requested `ST[01]` verification stages. + pub ack: AckFlags, + /// ECSS service type (`ST[x]`). + pub service: u8, + /// ECSS message subtype (`TC[x,y]`). + pub subtype: u8, + /// Ground source identifier. + pub source_id: u16, +} + +/// Encodes a complete PUS-C Telecommand (`TC`) frame with trailing CRC-16-CCITT into `out`. +/// +/// Returns the total number of bytes written. +/// +/// # Errors +/// +/// Returns [`PusError::BufferTooSmall`] if `out` cannot hold `13 + app_data.len()` bytes. +pub fn encode_tc(params: &TcParams, app_data: &[u8], out: &mut [u8]) -> Result { + let total = PRIMARY_HEADER_LEN + TC_SECONDARY_HEADER_LEN + app_data.len() + PEC_LEN; + if out.len() < total { + return Err(PusError::BufferTooSmall { + required: total, + available: out.len(), + }); + } + + let word0: u16 = 0x1800 | (params.apid & 0x07FF); // TC (type 1), sec_hdr=1 + let word1: u16 = 0xC000 | (params.sequence_count & 0x3FFF); + let data_len = (total - PRIMARY_HEADER_LEN - 1) as u16; + + out[0..2].copy_from_slice(&word0.to_be_bytes()); + out[2..4].copy_from_slice(&word1.to_be_bytes()); + out[4..6].copy_from_slice(&data_len.to_be_bytes()); + + out[6] = (PUS_VERSION_C << 4) | params.ack.to_nibble(); + out[7] = params.service; + out[8] = params.subtype; + out[9..11].copy_from_slice(¶ms.source_id.to_be_bytes()); + + let app_end = 11 + app_data.len(); + out[11..app_end].copy_from_slice(app_data); + + let crc = crc16_ccitt(&out[..app_end]); + out[app_end..app_end + 2].copy_from_slice(&crc.to_be_bytes()); + + Ok(total) +} diff --git a/crates/xtce-pus/src/services.rs b/crates/xtce-pus/src/services.rs new file mode 100644 index 0000000..ba99634 --- /dev/null +++ b/crates/xtce-pus/src/services.rs @@ -0,0 +1,263 @@ +//! ECSS-E-ST-70-41C service payload decoders and encoders (`ST[01]`, `ST[03]`, `ST[05]`, `ST[17]`). + +use crate::packet::{PusError, PusPacket}; + +/// ECSS Service 1 (`ST[01]`) Request Verification telemetry report. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum VerificationReport { + /// `TM[1,1]` — Telecommand acceptance verification succeeded. + AcceptanceSuccess { + /// 32-bit CCSDS Request ID of the accepted telecommand. + request_id: u32, + }, + /// `TM[1,2]` — Telecommand acceptance verification failed. + AcceptanceFailure { + /// 32-bit CCSDS Request ID of the rejected telecommand. + request_id: u32, + /// Mission-defined failure reason code. + failure_code: u16, + }, + /// `TM[1,3]` — Telecommand start of execution succeeded. + ExecutionStartSuccess { + /// 32-bit CCSDS Request ID of the started telecommand. + request_id: u32, + }, + /// `TM[1,7]` — Telecommand completion of execution succeeded. + ExecutionCompleteSuccess { + /// 32-bit CCSDS Request ID of the completed telecommand. + request_id: u32, + }, + /// `TM[1,8]` — Telecommand completion of execution failed. + ExecutionCompleteFailure { + /// 32-bit CCSDS Request ID of the failed telecommand. + request_id: u32, + /// Mission-defined failure reason code. + failure_code: u16, + }, +} + +/// ECSS Service 3 (`ST[03]`) Housekeeping & Diagnostic message. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum HousekeepingMessage<'a> { + /// `TC[3,5]` — Enable periodic generation of housekeeping structure `sid`. + EnablePeriodic { + /// Structure Identifier (`SID`). + sid: u16, + }, + /// `TC[3,6]` — Disable periodic generation of housekeeping structure `sid`. + DisablePeriodic { + /// Structure Identifier (`SID`). + sid: u16, + }, + /// `TC[3,27]` — Request a one-shot housekeeping report for structure `sid`. + OneShotRequest { + /// Structure Identifier (`SID`). + sid: u16, + }, + /// `TM[3,25]` — Housekeeping parameter report for structure `sid`. + ParameterReport { + /// Structure Identifier (`SID`). + sid: u16, + /// Raw parameter values following the 16-bit `SID`. + parameters: &'a [u8], + }, +} + +/// Standard 9-octet On-Board Computer (OBC) housekeeping structure (`SID = 1`) for HIL testing. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct ObcHousekeeping { + /// Spacecraft uptime in seconds. + pub uptime_s: u32, + /// Primary power bus voltage in millivolts (e.g. `28_150` for 28.15 V). + pub bus_voltage_mv: u16, + /// OBC board temperature in centi-degrees Celsius (e.g. `2350` for 23.50 °C). + pub obc_temp_cdeg: i16, + /// Operational mode (`0 = SAFE`, `1 = IDLE`, `2 = NOMINAL`, `3 = SCIENCE`). + pub mode: u8, +} + +impl ObcHousekeeping { + /// Structure Identifier (`SID`) used for OBC core housekeeping in `TM[3,25]`. + pub const SID: u16 = 1; + + /// Encodes the structure into a 11-byte `TM[3,25]` application data payload (`SID` + 9 bytes). + #[must_use] + pub const fn to_app_data(self) -> [u8; 11] { + let sid = Self::SID.to_be_bytes(); + let up = self.uptime_s.to_be_bytes(); + let v = self.bus_voltage_mv.to_be_bytes(); + let t = self.obc_temp_cdeg.to_be_bytes(); + [ + sid[0], sid[1], up[0], up[1], up[2], up[3], v[0], v[1], t[0], t[1], self.mode, + ] + } + + /// Decodes an `ObcHousekeeping` payload from the `parameters` slice of a `TM[3,25]` report. + #[must_use] + pub const fn from_parameter_bytes(bytes: &[u8]) -> Option { + if bytes.len() < 9 { + return None; + } + let uptime_s = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); + let bus_voltage_mv = u16::from_be_bytes([bytes[4], bytes[5]]); + let obc_temp_cdeg = i16::from_be_bytes([bytes[6], bytes[7]]); + let mode = bytes[8]; + Some(Self { + uptime_s, + bus_voltage_mv, + obc_temp_cdeg, + mode, + }) + } +} + +/// Severity level of an ECSS Service 5 (`ST[05]`) on-board event report. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum EventSeverity { + /// `TM[5,1]` — Informative nominal event. + Informative = 1, + /// `TM[5,2]` — Low-severity anomaly (warning). + LowAnomaly = 2, + /// `TM[5,3]` — Medium-severity anomaly (recoverable fault). + MediumAnomaly = 3, + /// `TM[5,4]` — High-severity anomaly (critical fault / safe-mode trigger). + HighAnomaly = 4, +} + +/// ECSS Service 5 (`ST[05]`) Event Reporting telemetry payload. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct EventReport<'a> { + /// Event severity derived from subtype `1..=4`. + pub severity: EventSeverity, + /// Mission-defined Event Definition ID (`Event_ID`). + pub event_id: u16, + /// Auxiliary diagnostic bytes following the `Event_ID`. + pub aux_data: &'a [u8], +} + +/// ECSS Service 17 (`ST[17]`) Test service message. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum TestMessage { + /// `TC[17,1]` — Perform an Are-You-Alive connection test. + AreYouAliveCommand, + /// `TM[17,2]` — Are-You-Alive connection test report. + AreYouAliveReport, +} + +/// High-level decoded ECSS PUS service payload. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum PusService<'a> { + /// `ST[01]` Request Verification report. + Verification(VerificationReport), + /// `ST[03]` Housekeeping & Diagnostic message. + Housekeeping(HousekeepingMessage<'a>), + /// `ST[05]` Event Report. + Event(EventReport<'a>), + /// `ST[17]` Test service message. + Test(TestMessage), + /// Any other service/subtype pair with its raw application data slice. + Custom { + /// ECSS service type (`ST[x]`). + service: u8, + /// ECSS message subtype (`TM/TC[x,y]`). + subtype: u8, + /// Uninterpreted application data. + app_data: &'a [u8], + }, +} + +impl<'a> PusPacket<'a> { + /// Decodes the service-specific application data of this packet into a [`PusService`]. + /// + /// # Errors + /// + /// Returns [`PusError::MalformedServiceData`] if a known service/subtype has fewer + /// application data bytes than the ECSS standard mandates. + pub fn decode_service(&self) -> Result, PusError> { + let service = self.header.service(); + let subtype = self.header.subtype(); + let data = self.app_data; + + match (self.header.is_telecommand(), service, subtype) { + (false, 1, 1 | 3 | 7) => { + if data.len() < 4 { + return Err(PusError::MalformedServiceData { service, subtype }); + } + let request_id = u32::from_be_bytes([data[0], data[1], data[2], data[3]]); + let report = match subtype { + 1 => VerificationReport::AcceptanceSuccess { request_id }, + 3 => VerificationReport::ExecutionStartSuccess { request_id }, + _ => VerificationReport::ExecutionCompleteSuccess { request_id }, + }; + Ok(PusService::Verification(report)) + } + (false, 1, 2 | 8) => { + if data.len() < 6 { + return Err(PusError::MalformedServiceData { service, subtype }); + } + let request_id = u32::from_be_bytes([data[0], data[1], data[2], data[3]]); + let failure_code = u16::from_be_bytes([data[4], data[5]]); + let report = if subtype == 2 { + VerificationReport::AcceptanceFailure { + request_id, + failure_code, + } + } else { + VerificationReport::ExecutionCompleteFailure { + request_id, + failure_code, + } + }; + Ok(PusService::Verification(report)) + } + (true, 3, 5 | 6 | 27) => { + if data.len() < 2 { + return Err(PusError::MalformedServiceData { service, subtype }); + } + let sid = u16::from_be_bytes([data[0], data[1]]); + let msg = match subtype { + 5 => HousekeepingMessage::EnablePeriodic { sid }, + 6 => HousekeepingMessage::DisablePeriodic { sid }, + _ => HousekeepingMessage::OneShotRequest { sid }, + }; + Ok(PusService::Housekeeping(msg)) + } + (false, 3, 25) => { + if data.len() < 2 { + return Err(PusError::MalformedServiceData { service, subtype }); + } + let sid = u16::from_be_bytes([data[0], data[1]]); + Ok(PusService::Housekeeping( + HousekeepingMessage::ParameterReport { + sid, + parameters: &data[2..], + }, + )) + } + (false, 5, 1..=4) => { + if data.len() < 2 { + return Err(PusError::MalformedServiceData { service, subtype }); + } + let severity = match subtype { + 1 => EventSeverity::Informative, + 2 => EventSeverity::LowAnomaly, + 3 => EventSeverity::MediumAnomaly, + _ => EventSeverity::HighAnomaly, + }; + let event_id = u16::from_be_bytes([data[0], data[1]]); + Ok(PusService::Event(EventReport { + severity, + event_id, + aux_data: &data[2..], + })) + } + (true, 17, 1) => Ok(PusService::Test(TestMessage::AreYouAliveCommand)), + (false, 17, 2) => Ok(PusService::Test(TestMessage::AreYouAliveReport)), + _ => Ok(PusService::Custom { + service, + subtype, + app_data: data, + }), + } + } +} From a95190c171b38719f0fe08c2c3280c7b742d140a Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Wed, 18 Nov 2026 15:21:39 +0100 Subject: [PATCH 06/13] ci(release): align workspace dependency versions to 0.1.1 and add crates.io publish job Update workspace.dependencies versions to 0.1.1 so dependent crates resolve on crates.io, and add a topological crates.io publishing job to the release workflow when CARGO_REGISTRY_TOKEN is configured. --- .github/workflows/release.yml | 20 ++++++++++++++++++++ Cargo.toml | 6 +++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f487cb3..b677071 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -91,3 +91,23 @@ jobs: --title "$GITHUB_REF_NAME" \ --notes-file notes.md \ artifacts/*/*.tar.gz + + crates-io: + name: crates.io + needs: release + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Publish workspace crates to crates.io + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + run: | + if [ -z "$CARGO_REGISTRY_TOKEN" ]; then + echo "::notice::CARGO_REGISTRY_TOKEN is not set; skipping crates.io publish" + exit 0 + fi + for crate in xtce-pus xtce-model xtce-decode xtce-codegen xtce-cli; do + cargo publish -p "$crate" + done diff --git a/Cargo.toml b/Cargo.toml index 0909f61..19ed794 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,9 +15,9 @@ repository = "https://github.com/RustSpaceLab/xtce-rs" authors = ["Maciej Myszkiewicz"] [workspace.dependencies] -xtce-model = { path = "crates/xtce-model", version = "0.1.0" } -xtce-decode = { path = "crates/xtce-decode", version = "0.1.0" } -xtce-codegen = { path = "crates/xtce-codegen", version = "0.1.0" } +xtce-model = { path = "crates/xtce-model", version = "0.1.1" } +xtce-decode = { path = "crates/xtce-decode", version = "0.1.1" } +xtce-codegen = { path = "crates/xtce-codegen", version = "0.1.1" } xtce-pus = { path = "crates/xtce-pus", version = "0.1.1" } # Keep this list short and justified — see CONTRIBUTING.md rule 7. From 0143bf9db75f15be230b983189d004d321ce0f78 Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Wed, 18 Nov 2026 15:48:07 +0100 Subject: [PATCH 07/13] ci(publish): add automated crates.io workflow on release, tag, and main push Add a dedicated GitHub Actions workflow (.github/workflows/publish.yml) that automatically publishes and updates workspace crates (xtce-pus, xtce-model, xtce-decode, xtce-codegen, xtce-cli) in topological order on GitHub Release publication, v* tags, pushes to main, or manual dispatch. --- .github/workflows/publish.yml | 43 +++++++++++++++++++++++++++++++++++ .github/workflows/release.yml | 20 ---------------- 2 files changed, 43 insertions(+), 20 deletions(-) create mode 100644 .github/workflows/publish.yml diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..c217f0f --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,43 @@ +name: Publish to crates.io + +on: + release: + types: [published] + push: + branches: [main] + tags: ["v*"] + workflow_dispatch: + +env: + CARGO_TERM_COLOR: always + +jobs: + publish: + name: crates.io + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Publish workspace crates in topological order + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + run: | + if [ -z "$CARGO_REGISTRY_TOKEN" ]; then + echo "::notice::CARGO_REGISTRY_TOKEN is not set; skipping crates.io publish" + exit 0 + fi + for crate in xtce-pus xtce-model xtce-decode xtce-codegen xtce-cli; do + echo "=== Publishing $crate ===" + if output=$(cargo publish -p "$crate" 2>&1); then + echo "$output" + sleep 10 + else + echo "$output" + if echo "$output" | grep -qiE "already exists|already uploaded"; then + echo "::notice::$crate is already published at this version; continuing" + else + exit 1 + fi + fi + done diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b677071..f487cb3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -91,23 +91,3 @@ jobs: --title "$GITHUB_REF_NAME" \ --notes-file notes.md \ artifacts/*/*.tar.gz - - crates-io: - name: crates.io - needs: release - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - uses: Swatinem/rust-cache@v2 - - name: Publish workspace crates to crates.io - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} - run: | - if [ -z "$CARGO_REGISTRY_TOKEN" ]; then - echo "::notice::CARGO_REGISTRY_TOKEN is not set; skipping crates.io publish" - exit 0 - fi - for crate in xtce-pus xtce-model xtce-decode xtce-codegen xtce-cli; do - cargo publish -p "$crate" - done From 00e7389cde78e514705e1674d51bd0b19e18404d Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Wed, 18 Nov 2026 16:00:02 +0100 Subject: [PATCH 08/13] docs: enrich crate READMEs with badges, usage examples, and bump to 0.1.2 Add crates.io/docs.rs badges, installation instructions, and runnable code/CLI examples across all workspace crate READMEs and root README.md, and bump workspace version to 0.1.2. --- Cargo.lock | 14 ++++---- Cargo.toml | 10 +++--- README.md | 17 +++++++--- crates/xtce-cli/README.md | 37 +++++++++++++++++---- crates/xtce-codegen/README.md | 14 ++++++++ crates/xtce-decode/README.md | 27 ++++++++++++++++ crates/xtce-model/README.md | 24 +++++++++++--- crates/xtce-pus/README.md | 60 ++++++++++++++++++++++++++++++++--- 8 files changed, 173 insertions(+), 30 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8185d70..fc462c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -915,7 +915,7 @@ checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" [[package]] name = "xtask" -version = "0.1.1" +version = "0.1.2" dependencies = [ "clap", "serde_json", @@ -925,7 +925,7 @@ dependencies = [ [[package]] name = "xtce-cli" -version = "0.1.1" +version = "0.1.2" dependencies = [ "clap", "xtce-codegen", @@ -936,7 +936,7 @@ dependencies = [ [[package]] name = "xtce-codegen" -version = "0.1.1" +version = "0.1.2" dependencies = [ "criterion", "prettyplease", @@ -950,7 +950,7 @@ dependencies = [ [[package]] name = "xtce-codegen-e2e" -version = "0.1.1" +version = "0.1.2" dependencies = [ "xtce-codegen", "xtce-decode", @@ -959,7 +959,7 @@ dependencies = [ [[package]] name = "xtce-decode" -version = "0.1.1" +version = "0.1.2" dependencies = [ "criterion", "proptest", @@ -969,7 +969,7 @@ dependencies = [ [[package]] name = "xtce-model" -version = "0.1.1" +version = "0.1.2" dependencies = [ "criterion", "proptest", @@ -979,7 +979,7 @@ dependencies = [ [[package]] name = "xtce-pus" -version = "0.1.1" +version = "0.1.2" [[package]] name = "zerocopy" diff --git a/Cargo.toml b/Cargo.toml index 19ed794..41a9e1e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ members = ["crates/*", "xtask"] exclude = ["crates/xtce-py"] [workspace.package] -version = "0.1.1" +version = "0.1.2" edition = "2024" rust-version = "1.85" license = "MIT OR Apache-2.0" @@ -15,10 +15,10 @@ repository = "https://github.com/RustSpaceLab/xtce-rs" authors = ["Maciej Myszkiewicz"] [workspace.dependencies] -xtce-model = { path = "crates/xtce-model", version = "0.1.1" } -xtce-decode = { path = "crates/xtce-decode", version = "0.1.1" } -xtce-codegen = { path = "crates/xtce-codegen", version = "0.1.1" } -xtce-pus = { path = "crates/xtce-pus", version = "0.1.1" } +xtce-model = { path = "crates/xtce-model", version = "0.1.2" } +xtce-decode = { path = "crates/xtce-decode", version = "0.1.2" } +xtce-codegen = { path = "crates/xtce-codegen", version = "0.1.2" } +xtce-pus = { path = "crates/xtce-pus", version = "0.1.2" } # Keep this list short and justified — see CONTRIBUTING.md rule 7. anyhow = "1" diff --git a/README.md b/README.md index 1e9a352..ab865d1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # xtce-rs [![CI](https://github.com/RustSpaceLab/xtce-rs/actions/workflows/ci.yml/badge.svg)](https://github.com/RustSpaceLab/xtce-rs/actions/workflows/ci.yml) +[![crates.io](https://img.shields.io/crates/v/xtce-cli.svg)](https://crates.io/crates/xtce-cli) +[![docs.rs](https://docs.rs/xtce-decode/badge.svg)](https://docs.rs/xtce-decode) Decode CCSDS telemetry packets in Rust, according to an [XTCE](https://www.omg.org/spec/XTCE/) definition. Part of [RustSpaceLab](https://github.com/RustSpaceLab). @@ -13,10 +15,11 @@ validated against that same implementation packet for packet. | Crate | What it does | |---|---| -| `xtce-model` | XTCE XML → arena-backed IR, reference resolution, validation; telemetry and telecommands | -| `xtce-decode` | IR + `&[u8]` → parameter values | -| `xtce-codegen` | IR → a static Rust decoder with every offset baked in | -| `xtce-cli` | `xtce info`, `xtce decode`, `xtce codegen`, `xtce bench` | +| [`xtce-model`](https://crates.io/crates/xtce-model) | XTCE XML → arena-backed IR, reference resolution, validation; telemetry and telecommands | +| [`xtce-decode`](https://crates.io/crates/xtce-decode) | IR + `&[u8]` / `PacketReader` → parameter values | +| [`xtce-codegen`](https://crates.io/crates/xtce-codegen) | IR → a static Rust decoder with every offset baked in | +| [`xtce-pus`](https://crates.io/crates/xtce-pus) | `#![no_std]` ECSS-E-ST-70-41C (PUS-C) framing, CRC-16-CCITT, and HIL OBC responder | +| [`xtce-cli`](https://crates.io/crates/xtce-cli) | `xtce info`, `xtce decode`, `xtce codegen`, `xtce wireshark`, `xtce pcap`, `xtce pus`, `xtce bench` | | `xtce-py` | Python bindings (PyO3), built by `maturin` | | `xtask` | differential test harness against the Python reference | @@ -66,12 +69,18 @@ back — see [`SUPPORTED.md`](SUPPORTED.md). #### Try it ```console +$ cargo install xtce-cli $ cargo run --release -p xtce-cli -- info testdata/spp/ctim/ctim_xtce_v1.xml $ cargo run --release -p xtce-cli -- decode \ testdata/spp/jpss/jpss1_geolocation_xtce_v1.xml \ testdata/spp/jpss/J01_G011_LZ_2021-04-09T00-00-00Z_V01.DAT1 --limit 3 --raw $ cargo run --release -p xtce-cli -- codegen \ testdata/spp/jpss/jpss1_geolocation_xtce_v1.xml +$ cargo run --release -p xtce-cli -- wireshark \ + testdata/spp/jpss/jpss1_geolocation_xtce_v1.xml --udp-port 5005 +$ cargo run --release -p xtce-cli -- pcap \ + testdata/spp/jpss/J01_G011_LZ_2021-04-09T00-00-00Z_V01.DAT1 --limit 10 -o jpss.pcap +$ cargo run --release -p xtce-cli -- pus --hil-demo $ cargo xtask diff $ cargo bench ``` diff --git a/crates/xtce-cli/README.md b/crates/xtce-cli/README.md index 4f93e93..6c9ec38 100644 --- a/crates/xtce-cli/README.md +++ b/crates/xtce-cli/README.md @@ -1,14 +1,39 @@ # xtce-cli -The `xtce` command: inspect an XTCE definition and decode a CCSDS stream against it. +[![crates.io](https://img.shields.io/crates/v/xtce-cli.svg)](https://crates.io/crates/xtce-cli) + +The `xtce` command-line tool: inspect XTCE definitions, stream-decode CCSDS telemetry, compile +static Rust decoders and Wireshark Lua dissectors, convert raw recordings to `.pcap`, and run +ECSS-E-ST-70-41C (PUS-C) Hardware-in-the-Loop (HIL) sessions. + +## Installation ```console -$ xtce info mission.xml # what it contains, and what cannot be decoded -$ xtce decode mission.xml downlink.dat # values, as a table or as JSON lines -$ xtce decode mission.xml downlink.dat --param 'ADGPSPOS*' +$ cargo install xtce-cli ``` -`--param` takes a glob, and a value matching nothing in the definition is an error naming the -nearest parameter rather than an empty report. +## Usage + +```console +# 1. Inspect an XTCE definition (parameters, containers, telecommands) +$ xtce info mission.xml --verbose + +# 2. Decode a CCSDS packet stream (from a file or '-' standard input) as a table, JSONL, or CSV +$ xtce decode mission.xml downlink.dat --format table +$ xtce decode mission.xml downlink.dat --format csv --raw > telemetry.csv +$ cat downlink.dat | xtce decode mission.xml - --param 'ADGPSPOS*' --no-summary + +# 3. Compile an XTCE definition into a zero-allocation static Rust decoder +$ xtce codegen mission.xml -o decoder.rs + +# 4. Generate a standalone Wireshark Lua dissector and wrap raw CCSDS frames in a .pcap file +$ xtce wireshark mission.xml --udp-port 5005 -o mission.lua +$ xtce pcap downlink.dat -o downlink.pcap +$ wireshark -X lua_script:mission.lua downlink.pcap + +# 5. Inspect ECSS-E-ST-70-41C (PUS-C) frames or run a closed-loop OBC HIL session +$ xtce pus --hil-demo -o hil_session.bin +$ xtce pus hil_session.bin +``` Part of [RustSpaceLab/xtce-rs](https://github.com/RustSpaceLab/xtce-rs). diff --git a/crates/xtce-codegen/README.md b/crates/xtce-codegen/README.md index 8fe21d8..aa9f500 100644 --- a/crates/xtce-codegen/README.md +++ b/crates/xtce-codegen/README.md @@ -1,5 +1,8 @@ # xtce-codegen +[![crates.io](https://img.shields.io/crates/v/xtce-codegen.svg)](https://crates.io/crates/xtce-codegen) +[![docs.rs](https://docs.rs/xtce-codegen/badge.svg)](https://docs.rs/xtce-codegen) + Compiles an XTCE definition into a `struct` per container whose `decode` is a sequence of loads, shifts and masks with every offset already a literal. Nothing consults the XTCE model at run time. @@ -11,4 +14,15 @@ Refusals are fatal by design. A construct the generator cannot compile is refuse element named, rather than falling back to interpretation — a silent fallback would make the measurement above meaningless. +## Example + +```rust,no_run +use xtce_model::XtceDb; + +let db = XtceDb::from_path("mission.xml")?; +let source = xtce_codegen::generate(&db, &xtce_codegen::Options::default())?; +std::fs::write("decoder.rs", source)?; +# Ok::<(), Box>(()) +``` + Part of [RustSpaceLab/xtce-rs](https://github.com/RustSpaceLab/xtce-rs). diff --git a/crates/xtce-decode/README.md b/crates/xtce-decode/README.md index d990124..1f59973 100644 --- a/crates/xtce-decode/README.md +++ b/crates/xtce-decode/README.md @@ -1,5 +1,8 @@ # xtce-decode +[![crates.io](https://img.shields.io/crates/v/xtce-decode.svg)](https://crates.io/crates/xtce-decode) +[![docs.rs](https://docs.rs/xtce-decode/badge.svg)](https://docs.rs/xtce-decode) + Decodes CCSDS space packets against an XTCE definition, and is tested the only way that means anything: packet for packet against [`lasp/space_packet_parser`](https://github.com/lasp/space_packet_parser), the Python @@ -11,9 +14,33 @@ Measured at roughly 100× that reference on decode. * **No panics.** Every failure is a `DecodeError`; a corrupt or hostile packet must not take down a process sitting on a live downlink. +* **Constant-memory streaming.** `PacketReader` frames CCSDS packets sequentially from any + `std::io::Read` source into a single reusable buffer ($\le 64\text{ KiB}$). * **No allocation for aligned reads.** Byte-aligned binary and string fields borrow straight from the packet. * **Raw and engineering values both kept.** XTCE treats them as distinct and restriction criteria may test either. +## Example + +```rust,no_run +use std::fs::File; +use std::io::BufReader; +use xtce_decode::{Decoder, PacketReader}; +use xtce_model::XtceDb; + +let db = XtceDb::from_path("mission.xml")?; +let decoder = Decoder::new(&db)?; + +let file = File::open("downlink.bin")?; +let mut reader = PacketReader::new(BufReader::new(file), 0); +while let Some(framed) = reader.next_packet()? { + let packet = decoder.decode(framed.bytes())?; + for (name, val) in packet.iter_named() { + println!("{name} = {} (raw {})", val.eng, val.raw); + } +} +# Ok::<(), Box>(()) +``` + Part of [RustSpaceLab/xtce-rs](https://github.com/RustSpaceLab/xtce-rs). diff --git a/crates/xtce-model/README.md b/crates/xtce-model/README.md index 2d4a70e..123e283 100644 --- a/crates/xtce-model/README.md +++ b/crates/xtce-model/README.md @@ -1,15 +1,31 @@ # xtce-model +[![crates.io](https://img.shields.io/crates/v/xtce-model.svg)](https://crates.io/crates/xtce-model) +[![docs.rs](https://docs.rs/xtce-model/badge.svg)](https://docs.rs/xtce-model) + Reads an XTCE `SpaceSystem` document into `XtceDb`: a flat, index-addressed model that [`xtce-decode`](https://crates.io/crates/xtce-decode) walks to decode CCSDS packets, and that -`xtce-codegen` compiles into static Rust decoders. +[`xtce-codegen`](https://crates.io/crates/xtce-codegen) compiles into static Rust decoders. Streaming XML through `quick-xml`, an arena behind every entity, and a `u32` newtype instead of a pointer — which keeps the model `Send + Sync`, makes cloning cheap, and turns following a reference into an array index. -Only `TelemetryMetaData` is modelled. Constructs outside the decodable subset are still -*represented*, so loading a real mission database never fails merely because part of it is out -of scope; the error comes later, from the decoder, at the point a value actually depends on it. +Models both `TelemetryMetaData` and `CommandMetaData` (including telecommand arguments, +argument assignments, and fixed-value entries). Constructs outside the decodable subset are +still *represented*, so loading a real mission database never fails merely because part of it +is out of scope; the error comes later, from the decoder, at the point a value actually depends +on it. + +## Example + +```rust,no_run +use xtce_model::XtceDb; + +let db = XtceDb::from_path("mission.xml")?; +let stats = db.stats(); +println!("{} parameters, {} containers, {} commands", stats.parameters, stats.containers, stats.commands); +# Ok::<(), xtce_model::LoadError>(()) +``` Part of [RustSpaceLab/xtce-rs](https://github.com/RustSpaceLab/xtce-rs). diff --git a/crates/xtce-pus/README.md b/crates/xtce-pus/README.md index 3f6fb18..8f0d663 100644 --- a/crates/xtce-pus/README.md +++ b/crates/xtce-pus/README.md @@ -1,5 +1,8 @@ # xtce-pus +[![crates.io](https://img.shields.io/crates/v/xtce-pus.svg)](https://crates.io/crates/xtce-pus) +[![docs.rs](https://docs.rs/xtce-pus/badge.svg)](https://docs.rs/xtce-pus) + `#![no_std]`, zero-allocation implementation of the European Cooperation for Space Standardization **ECSS-E-ST-70-41C Packet Utilization Standard (PUS-C)** over CCSDS 133.0-B Space Packets, with a bare-metal Hardware-in-the-Loop (HIL) spacecraft responder. @@ -7,10 +10,59 @@ Space Packets, with a bare-metal Hardware-in-the-Loop (HIL) spacecraft responder ## Capabilities - **CRC-16-CCITT (`0x1021`, initial `0xFFFF`)** per ECSS-E-ST-70-41C Annex B (compile-time lookup table, zero branches). -- **PUS-C Telemetry (`TM`) and Telecommand (`TC`) secondary headers**, including CUC (4+2 octet) spacecraft time and telecommand acknowledgement flags. +- **PUS-C Telemetry (`TM`) and Telecommand (`TC`) secondary headers**, including CUC (4+2 octet) spacecraft time and telecommand acknowledgement flags (`AckFlags`). - **Core ECSS PUS Services**: - - **ST\[01\] Request Verification**: `TM[1,1]` Acceptance Success, `TM[1,2]` Acceptance Failure, `TM[1,7]` Execution Complete Success, `TM[1,8]` Execution Complete Failure. - - **ST\[03\] Housekeeping**: `TC[3,5]` Enable HK, `TC[3,6]` Disable HK, `TC[3,27]` One-Shot HK Request, `TM[3,25]` Housekeeping Parameter Report. + - **ST\[01\] Request Verification**: `TM[1,1]` Acceptance Success, `TM[1,2]` Acceptance Failure, `TM[1,3]` Execution Start, `TM[1,7]` Execution Complete Success, `TM[1,8]` Execution Complete Failure. + - **ST\[03\] Housekeeping**: `TC[3,5]` Enable HK, `TC[3,6]` Disable HK, `TC[3,27]` One-Shot HK Request, `TM[3,25]` Housekeeping Parameter Report (`ObcHousekeeping`). - **ST\[05\] Event Reporting**: `TM[5,1]` Informative Event through `TM[5,4]` High-Severity Anomaly. - **ST\[17\] Test Service**: `TC[17,1]` Are-You-Alive Connection Test and `TM[17,2]` Are-You-Alive Connection Report. -- **`PusResponder` HIL State Machine**: zero-heap flight responder suitable for `thumbv7em-none-eabihf` (STM32), RISC-V (ESP32), or desktop HIL benches. +- **`PusResponder` HIL State Machine**: deterministic, zero-heap flight responder suitable for `thumbv7em-none-eabihf` (STM32 Cortex-M), RISC-V (ESP32), RP2040/RP2350, or desktop HIL benches. + +## Installation + +```toml +[dependencies] +xtce-pus = "0.1" +``` + +## Example: Closed-Loop `ST[17]` Ping & `ST[01]` Verification (`#![no_std]`) + +```rust +use xtce_pus::{ + AckFlags, MAX_HIL_FRAME_LEN, PusPacket, PusResponder, PusService, TcParams, TestMessage, + VerificationReport, encode_tc, +}; + +let mut obc = PusResponder::new(0x010, 0x0001); + +// 1. Ground encodes a TC[17,1] Are-You-Alive telecommand into a stack buffer +let mut tc_buf = [0u8; 32]; +let tc_len = encode_tc( + &TcParams { + apid: 0x010, + sequence_count: 1, + ack: AckFlags::ACCEPT_AND_COMPLETE, + service: 17, + subtype: 1, + source_id: 0x0042, + }, + &[], + &mut tc_buf, +)?; + +// 2. Bare-metal OBC responder processes the telecommand without heap allocations +let mut tm_frames = [[0u8; MAX_HIL_FRAME_LEN]; 4]; +let mut tm_lens = [0usize; 4]; +let emitted = obc.process_telecommand(&tc_buf[..tc_len], &mut tm_frames, &mut tm_lens)?; +assert_eq!(emitted, 3); // TM[1,1] Acceptance + TM[17,2] Alive Report + TM[1,7] Complete + +// 3. Ground parses and verifies the downlinked TM[17,2] frame (including CRC-16-CCITT) +let report = PusPacket::parse(&tm_frames[1][..tm_lens[1]])?; +assert_eq!( + report.decode_service()?, + PusService::Test(TestMessage::AreYouAliveReport) +); +# Ok::<(), xtce_pus::PusError>(()) +``` + +Part of [RustSpaceLab/xtce-rs](https://github.com/RustSpaceLab/xtce-rs). From 08a3b484a9043bdcadcceb00d34c3d947a6d87ee Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Wed, 18 Nov 2026 23:48:39 +0100 Subject: [PATCH 09/13] feat(pus): add ST[06/08/11/12], SipHash-2-4 TC security gate, and PUS XTCE emitter Expand xtce-pus and xtce-cli for Earth Observation and dual-use mission profiles: - Add ST[06] On-Board Memory Management (load, dump, CRC-16-CCITT scrubbing) - Add ST[08] Function Management (EO optical capture, DPU AI inference, safe mode) - Add ST[11] Time-Based Scheduling and ST[12] On-Board Monitoring (FDIR) - Add TcSecurityGate (#![no_std] constant-time SipHash-2-4 MAC + anti-replay counter) - Add 'xtce pus --emit-xtce' to emit a complete XTCE 1.2 XML database for ECSS PUS-C frames --- Cargo.lock | 14 +- Cargo.toml | 10 +- crates/xtce-cli/README.md | 5 +- crates/xtce-cli/src/main.rs | 10 +- crates/xtce-cli/src/pus.rs | 464 +++++++++++++++++++++++++++++++- crates/xtce-pus/README.md | 5 + crates/xtce-pus/src/hil.rs | 247 +++++++++++++++-- crates/xtce-pus/src/lib.rs | 167 +++++++++++- crates/xtce-pus/src/security.rs | 241 +++++++++++++++++ crates/xtce-pus/src/services.rs | 392 +++++++++++++++++++++++++-- 10 files changed, 1469 insertions(+), 86 deletions(-) create mode 100644 crates/xtce-pus/src/security.rs diff --git a/Cargo.lock b/Cargo.lock index fc462c9..ac4f646 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -915,7 +915,7 @@ checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" [[package]] name = "xtask" -version = "0.1.2" +version = "0.1.3" dependencies = [ "clap", "serde_json", @@ -925,7 +925,7 @@ dependencies = [ [[package]] name = "xtce-cli" -version = "0.1.2" +version = "0.1.3" dependencies = [ "clap", "xtce-codegen", @@ -936,7 +936,7 @@ dependencies = [ [[package]] name = "xtce-codegen" -version = "0.1.2" +version = "0.1.3" dependencies = [ "criterion", "prettyplease", @@ -950,7 +950,7 @@ dependencies = [ [[package]] name = "xtce-codegen-e2e" -version = "0.1.2" +version = "0.1.3" dependencies = [ "xtce-codegen", "xtce-decode", @@ -959,7 +959,7 @@ dependencies = [ [[package]] name = "xtce-decode" -version = "0.1.2" +version = "0.1.3" dependencies = [ "criterion", "proptest", @@ -969,7 +969,7 @@ dependencies = [ [[package]] name = "xtce-model" -version = "0.1.2" +version = "0.1.3" dependencies = [ "criterion", "proptest", @@ -979,7 +979,7 @@ dependencies = [ [[package]] name = "xtce-pus" -version = "0.1.2" +version = "0.1.3" [[package]] name = "zerocopy" diff --git a/Cargo.toml b/Cargo.toml index 41a9e1e..ca4fa12 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ members = ["crates/*", "xtask"] exclude = ["crates/xtce-py"] [workspace.package] -version = "0.1.2" +version = "0.1.3" edition = "2024" rust-version = "1.85" license = "MIT OR Apache-2.0" @@ -15,10 +15,10 @@ repository = "https://github.com/RustSpaceLab/xtce-rs" authors = ["Maciej Myszkiewicz"] [workspace.dependencies] -xtce-model = { path = "crates/xtce-model", version = "0.1.2" } -xtce-decode = { path = "crates/xtce-decode", version = "0.1.2" } -xtce-codegen = { path = "crates/xtce-codegen", version = "0.1.2" } -xtce-pus = { path = "crates/xtce-pus", version = "0.1.2" } +xtce-model = { path = "crates/xtce-model", version = "0.1.3" } +xtce-decode = { path = "crates/xtce-decode", version = "0.1.3" } +xtce-codegen = { path = "crates/xtce-codegen", version = "0.1.3" } +xtce-pus = { path = "crates/xtce-pus", version = "0.1.3" } # Keep this list short and justified — see CONTRIBUTING.md rule 7. anyhow = "1" diff --git a/crates/xtce-cli/README.md b/crates/xtce-cli/README.md index 6c9ec38..8087a31 100644 --- a/crates/xtce-cli/README.md +++ b/crates/xtce-cli/README.md @@ -31,9 +31,10 @@ $ xtce wireshark mission.xml --udp-port 5005 -o mission.lua $ xtce pcap downlink.dat -o downlink.pcap $ wireshark -X lua_script:mission.lua downlink.pcap -# 5. Inspect ECSS-E-ST-70-41C (PUS-C) frames or run a closed-loop OBC HIL session +# 5. Inspect ECSS-E-ST-70-41C (PUS-C) frames, run an EO HIL session, or emit a PUS XTCE database $ xtce pus --hil-demo -o hil_session.bin -$ xtce pus hil_session.bin +$ xtce pus --emit-xtce -o ecss_pus.xml +$ xtce decode ecss_pus.xml hil_session.bin --format table ``` Part of [RustSpaceLab/xtce-rs](https://github.com/RustSpaceLab/xtce-rs). diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index f2d2717..8d643ee 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -134,7 +134,7 @@ enum Command { limit: Option, }, - /// Inspect ECSS-E-ST-70-41C (PUS-C) packet streams or run a closed-loop HIL OBC session. + /// Inspect ECSS-E-ST-70-41C (PUS-C) packet streams, run a HIL OBC session, or emit XTCE XML. Pus { /// File of concatenated CCSDS/PUS packets. Use '-' to read from standard input. packets: Option, @@ -143,7 +143,11 @@ enum Command { #[arg(long)] hil_demo: bool, - /// Write HIL session packets to this raw stream file. + /// Emit a complete XTCE 1.2 XML mission definition for the ECSS PUS-C spacecraft profile. + #[arg(long)] + emit_xtce: bool, + + /// Write output (HIL capture or emitted XTCE XML) to this file. #[arg(long, short)] out: Option, @@ -245,12 +249,14 @@ fn run(cli: Cli) -> Result<(), Box> { Command::Pus { packets, hil_demo, + emit_xtce, out, skip_header_bytes, limit, } => pus::run(&pus::Options { packets: packets.as_deref(), hil_demo, + emit_xtce, out: out.as_deref(), skip_header_bytes, limit, diff --git a/crates/xtce-cli/src/pus.rs b/crates/xtce-cli/src/pus.rs index 6e7dcda..e4b83fd 100644 --- a/crates/xtce-cli/src/pus.rs +++ b/crates/xtce-cli/src/pus.rs @@ -1,18 +1,21 @@ -//! `xtce pus` — inspect ECSS-E-ST-70-41C (PUS-C) packet streams and run closed-loop HIL demos. +//! `xtce pus` — inspect ECSS-E-ST-70-41C (PUS-C) packet streams, run closed-loop HIL demos, +//! and emit a matching XTCE 1.2 mission database (`--emit-xtce`). use std::io::{Read, Write}; use std::path::Path; use xtce_decode::PacketReader; use xtce_pus::{ - AckFlags, HousekeepingMessage, MAX_HIL_FRAME_LEN, ObcHousekeeping, PusError, PusHeader, - PusPacket, PusResponder, PusService, TcParams, TestMessage, VerificationReport, encode_tc, + AckFlags, FUNC_EO_OPTICAL_CAPTURE, HousekeepingMessage, MAX_HIL_FRAME_LEN, MemoryMessage, + MonitoringMessage, ObcHousekeeping, PusError, PusHeader, PusPacket, PusResponder, PusService, + ScheduleMessage, TcParams, TestMessage, VerificationReport, encode_tc, }; /// Configuration for `xtce pus`. pub struct Options<'a> { pub packets: Option<&'a Path>, pub hil_demo: bool, + pub emit_xtce: bool, pub out: Option<&'a Path>, pub skip_header_bytes: usize, pub limit: Option, @@ -31,8 +34,13 @@ fn open_packet_source(packets: &Path) -> std::io::Result> { /// /// # Errors /// -/// Returns an error if neither `--hil-demo` nor a packet source path is given, or if I/O fails. +/// Returns an error if no action (``, `--hil-demo`, or `--emit-xtce`) is specified or +/// if I/O fails. pub fn run(options: &Options<'_>) -> Result<(), Box> { + if options.emit_xtce { + return write_pus_xtce(options.out); + } + let stdout = std::io::stdout(); let mut out = std::io::BufWriter::new(stdout.lock()); @@ -43,7 +51,9 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { } let Some(packets_path) = options.packets else { - return Err("provide a packet stream file (or '-') or pass --hil-demo".into()); + return Err( + "provide a packet stream file (or '-'), pass --hil-demo, or pass --emit-xtce".into(), + ); }; let source = open_packet_source(packets_path)?; @@ -53,6 +63,17 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { Ok(()) } +fn write_pus_xtce(out_path: Option<&Path>) -> Result<(), Box> { + match out_path { + Some(path) if path.as_os_str() != "-" => { + std::fs::write(path, ECSS_PUS_XTCE_XML)?; + eprintln!("wrote ECSS PUS-C XTCE definition to {}", path.display()); + } + _ => print!("{ECSS_PUS_XTCE_XML}"), + } + Ok(()) +} + fn inspect_stream( reader: &mut PacketReader, out: &mut W, @@ -142,6 +163,15 @@ fn write_pus_packet( ev.event_id, ev.aux_data.len() ), + Ok(PusService::Memory(mem)) => write_memory_summary(out, &mem), + Ok(PusService::Function(call)) => writeln!( + out, + "PerformFunction(fn_id=0x{:04X}, args={}B)", + call.function_id, + call.args.len() + ), + Ok(PusService::Schedule(sched)) => write_schedule_summary(out, &sched), + Ok(PusService::Monitoring(mon)) => write_monitoring_summary(out, mon), Ok(PusService::Test(TestMessage::AreYouAliveCommand)) => { writeln!(out, "AreYouAliveCommand") } @@ -217,22 +247,125 @@ fn write_hk_summary(out: &mut impl Write, hk: &HousekeepingMessage<'_>) -> std:: } } +fn write_memory_summary(out: &mut impl Write, mem: &MemoryMessage<'_>) -> std::io::Result<()> { + match mem { + MemoryMessage::LoadRaw { + memory_id, + address, + data, + } => writeln!( + out, + "MemoryLoadRaw(mem={memory_id}, addr=0x{address:08X}, len={}B)", + data.len() + ), + MemoryMessage::DumpRawRequest { + memory_id, + address, + length, + } => writeln!( + out, + "MemoryDumpRequest(mem={memory_id}, addr=0x{address:08X}, len={length}B)" + ), + MemoryMessage::DumpRawReport { + memory_id, + address, + data, + } => writeln!( + out, + "MemoryDumpReport(mem={memory_id}, addr=0x{address:08X}, len={}B)", + data.len() + ), + MemoryMessage::CheckRawRequest { + memory_id, + address, + length, + } => writeln!( + out, + "MemoryCheckRequest(mem={memory_id}, addr=0x{address:08X}, len={length}B)" + ), + MemoryMessage::CheckRawReport { + memory_id, + address, + length, + checksum, + } => writeln!( + out, + "MemoryCheckReport(mem={memory_id}, addr=0x{address:08X}, len={length}B, crc=0x{checksum:04X})" + ), + } +} + +fn write_schedule_summary( + out: &mut impl Write, + sched: &ScheduleMessage<'_>, +) -> std::io::Result<()> { + match sched { + ScheduleMessage::Enable => writeln!(out, "ScheduleEnable"), + ScheduleMessage::Disable => writeln!(out, "ScheduleDisable"), + ScheduleMessage::Reset => writeln!(out, "ScheduleReset"), + ScheduleMessage::InsertActivity { + release_time_s, + activity_data, + } => writeln!( + out, + "ScheduleInsertActivity(release_t={release_time_s}s, payload={}B)", + activity_data.len() + ), + ScheduleMessage::SummaryReport { + enabled, + pending_count, + } => writeln!( + out, + "ScheduleSummaryReport(enabled={enabled}, pending={pending_count})" + ), + } +} + +fn write_monitoring_summary(out: &mut impl Write, mon: MonitoringMessage) -> std::io::Result<()> { + match mon { + MonitoringMessage::Enable => writeln!(out, "MonitoringEnable"), + MonitoringMessage::Disable => writeln!(out, "MonitoringDisable"), + MonitoringMessage::CheckTransitionReport { + param_id, + observed_value, + limit_value, + } => writeln!( + out, + "MonitoringTransition(param=0x{param_id:04X}, val={observed_value}, limit={limit_value})" + ), + } +} + fn run_hil_demo( out: &mut impl Write, capture_out: Option<&Path>, ) -> Result<(), Box> { writeln!( out, - "=== ECSS-E-ST-70-41C (PUS-C) Hardware-in-the-Loop (HIL) Closed-Loop Session ===" + "=== ECSS-E-ST-70-41C (PUS-C) Earth Observation HIL Closed-Loop Session ===" )?; let mut responder = PusResponder::new(0x010, 0x0001); - let mut recorded_stream: Vec = Vec::with_capacity(512); + let mut recorded_stream: Vec = Vec::with_capacity(1024); let mut frame_index = 0usize; let sid_bytes = ObcHousekeeping::SID.to_be_bytes(); - let steps: [(u8, u8, &[u8], bool); 4] = [ + let mem_load: [u8; 11] = [1, 0, 0, 0, 8, b'C', b'A', b'M', b'I', b'L', b'A']; + let mem_check: [u8; 7] = [1, 0, 0, 0, 8, 0, 6]; + let fn_eo_capture: [u8; 3] = [ + (FUNC_EO_OPTICAL_CAPTURE >> 8) as u8, + (FUNC_EO_OPTICAL_CAPTURE & 0xFF) as u8, + 0x01, + ]; + let sched_insert: [u8; 6] = [0x00, 0x00, 0x02, 0x58, 0x00, 0x20]; + + let steps: [(u8, u8, &[u8], bool); 9] = [ (17, 1, &[], false), (3, 5, &sid_bytes, false), + (6, 2, &mem_load, false), + (6, 9, &mem_check, false), + (8, 1, &fn_eo_capture, false), + (11, 1, &[], false), + (11, 4, &sched_insert, false), (3, 27, &sid_bytes, false), (17, 1, &[], true), ]; @@ -262,7 +395,6 @@ fn run_hil_demo( if let Ok(parsed_tc) = PusPacket::parse(&tc_buf[..tc_len]) { write_pus_packet(out, frame_index, &parsed_tc)?; - recorded_stream.extend_from_slice(&tc_buf[..tc_len]); } else { writeln!( out, @@ -286,7 +418,7 @@ fn run_hil_demo( if let Some(path) = capture_out { std::fs::write(path, &recorded_stream)?; eprintln!( - "wrote {} bytes of ECSS PUS HIL frames to {}", + "wrote {} bytes of ECSS PUS HIL telemetry frames to {}", recorded_stream.len(), path.display() ); @@ -295,12 +427,271 @@ fn run_hil_demo( Ok(()) } +/// Complete XTCE 1.2 XML mission definition describing the ECSS-E-ST-70-41C (PUS-C) +/// telemetry containers emitted by [`PusResponder`]. +pub const ECSS_PUS_XTCE_XML: &str = r#" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +"#; + #[cfg(test)] mod tests { - use super::run_hil_demo; + use xtce_decode::Decoder; + use xtce_model::XtceDb; + + use super::{ECSS_PUS_XTCE_XML, run_hil_demo}; #[test] - fn hil_demo_executes_all_four_ecss_pus_scenarios() { + fn hil_demo_executes_all_earth_observation_ecss_pus_scenarios() { let mut out = Vec::new(); run_hil_demo(&mut out, None).expect("hil demo succeeds"); let text = String::from_utf8(out).expect("utf8"); @@ -309,8 +700,57 @@ mod tests { assert!(text.contains("TM[17,2]")); assert!(text.contains("AcceptanceSuccess")); assert!(text.contains("EnablePeriodicHk(sid=1)")); + assert!(text.contains("MemoryLoadRaw(mem=1, addr=0x00000008, len=6B)")); + assert!(text.contains("MemoryCheckReport(mem=1, addr=0x00000008, len=6B")); + assert!(text.contains("PerformFunction(fn_id=0x0010, args=1B)")); + assert!(text.contains("ScheduleSummaryReport(enabled=true, pending=1)")); assert!(text.contains("ObcHkReport(sid=1")); + assert!(text.contains("mode=3")); assert!(text.contains("AcceptanceFailure")); assert!(text.contains("Event(LowAnomaly, id=0x0101")); } + + #[test] + fn emitted_pus_xtce_database_decodes_hil_packets_and_compiles_wireshark_lua() { + let db = XtceDb::from_xml(ECSS_PUS_XTCE_XML).expect("PUS XTCE XML loads"); + let decoder = Decoder::new(&db).expect("decoder initializes"); + + // Verify the emitted XTCE definition also compiles cleanly into a Wireshark Lua dissector + let lua = + crate::wireshark::generate_lua(&db, None, "ecss_pus.xml", Some(5006)).expect("lua"); + assert!(lua.contains("TM_3_25_ObcHousekeeping")); + assert!(lua.contains("TM_6_10_MemoryCheckReport")); + + // Verify a live TM[3,25] frame from PusResponder decodes through xtce_decode::Decoder + let mut responder = xtce_pus::PusResponder::new(0x010, 0x0001); + let sid_bytes = xtce_pus::ObcHousekeeping::SID.to_be_bytes(); + let mut tc_buf = [0u8; 32]; + let tc_len = xtce_pus::encode_tc( + &xtce_pus::TcParams { + apid: 0x010, + sequence_count: 1, + ack: xtce_pus::AckFlags::ACCEPT_AND_COMPLETE, + service: 3, + subtype: 27, + source_id: 0x0042, + }, + &sid_bytes, + &mut tc_buf, + ) + .expect("TC[3,27]"); + + let mut tm_frames = [[0u8; xtce_pus::MAX_HIL_FRAME_LEN]; 4]; + let mut tm_lens = [0usize; 4]; + let count = responder + .process_telecommand(&tc_buf[..tc_len], &mut tm_frames, &mut tm_lens) + .expect("HIL responds"); + assert_eq!(count, 3); + + for slot in 0..count { + let packet = decoder + .decode(&tm_frames[slot][..tm_lens[slot]]) + .expect("XTCE decodes ECSS PUS frame"); + assert!(packet.len() >= 15); + } + } } diff --git a/crates/xtce-pus/README.md b/crates/xtce-pus/README.md index 8f0d663..5de5d2f 100644 --- a/crates/xtce-pus/README.md +++ b/crates/xtce-pus/README.md @@ -15,7 +15,12 @@ Space Packets, with a bare-metal Hardware-in-the-Loop (HIL) spacecraft responder - **ST\[01\] Request Verification**: `TM[1,1]` Acceptance Success, `TM[1,2]` Acceptance Failure, `TM[1,3]` Execution Start, `TM[1,7]` Execution Complete Success, `TM[1,8]` Execution Complete Failure. - **ST\[03\] Housekeeping**: `TC[3,5]` Enable HK, `TC[3,6]` Disable HK, `TC[3,27]` One-Shot HK Request, `TM[3,25]` Housekeeping Parameter Report (`ObcHousekeeping`). - **ST\[05\] Event Reporting**: `TM[5,1]` Informative Event through `TM[5,4]` High-Severity Anomaly. + - **ST\[06\] On-Board Memory Management**: `TC[6,2]` Load Raw Memory, `TC[6,5]` / `TM[6,6]` Dump Raw Memory, `TC[6,9]` / `TM[6,10]` CRC-16-CCITT Memory Scrubbing Check. + - **ST\[08\] Function Management**: `TC[8,1]` Perform Function (e.g., EO optical capture, on-board DPU AI inference, safe-mode transition). + - **ST\[11\] Time-Based Scheduling**: `TC[11,1..3]` Enable/Disable/Reset Schedule, `TC[11,4]` Insert Time-Tagged Activity, `TM[11,13]` Schedule Summary Report. + - **ST\[12\] On-Board Monitoring (FDIR)**: `TC[12,1..2]` Enable/Disable Parameter Monitoring, `TM[12,12]` Check Transition Report. - **ST\[17\] Test Service**: `TC[17,1]` Are-You-Alive Connection Test and `TM[17,2]` Are-You-Alive Connection Report. +- **Dual-Use Telecommand Security (`TcSecurityGate`)**: constant-time 64-bit **SipHash-2-4 MAC** verification and monotonic 32-bit **Anti-Replay** counter protection for critical uplink commands. - **`PusResponder` HIL State Machine**: deterministic, zero-heap flight responder suitable for `thumbv7em-none-eabihf` (STM32 Cortex-M), RISC-V (ESP32), RP2040/RP2350, or desktop HIL benches. ## Installation diff --git a/crates/xtce-pus/src/hil.rs b/crates/xtce-pus/src/hil.rs index 34cc9cc..4f892a1 100644 --- a/crates/xtce-pus/src/hil.rs +++ b/crates/xtce-pus/src/hil.rs @@ -3,21 +3,25 @@ //! `PusResponder` implements a deterministic, zero-allocation spacecraft command and telemetry //! handler suitable for flashing onto an STM32 (`thumbv7em-none-eabihf`), RP2040/RP2350, or //! ESP32 microcontroller connected over UART/CAN/UDP, as well as running in closed-loop -//! desktop integration tests. +//! desktop integration tests for Earth Observation and dual-use constellations. +use crate::crc::crc16_ccitt; use crate::packet::{CucTimestamp, PusError, PusHeader, PusPacket, TmParams, encode_tm}; use crate::services::ObcHousekeeping; -///Maximum byte size of a single response frame emitted by [`PusResponder`]. +/// Maximum byte size of a single response frame emitted by [`PusResponder`]. pub const MAX_HIL_FRAME_LEN: usize = 64; +/// Size of the on-board scratchpad RAM partition (`Memory_ID = 1`) managed by `ST[06]`. +pub const OBC_SCRATCHPAD_LEN: usize = 64; + /// Failure code reported in `TM[1,2]` when a telecommand fails CRC-16-CCITT verification. pub const ERR_CODE_CRC_MISMATCH: u16 = 0xBAD0; /// Failure code reported in `TM[1,2]` when a frame is not a telecommand. pub const ERR_CODE_NOT_A_TC: u16 = 0xBAD1; -/// Failure code reported in `TM[1,8]` when a service, subtype, or `SID` is unsupported. +/// Failure code reported in `TM[1,8]` when a service, subtype, or argument is unsupported. pub const ERR_CODE_UNSUPPORTED: u16 = 0x0404; /// Event ID emitted in `TM[5,2]` when a corrupted telecommand is rejected. @@ -26,8 +30,24 @@ pub const EVENT_ID_CORRUPTED_TC: u16 = 0x0101; /// Event ID emitted in `TM[5,1]` when periodic housekeeping is enabled. pub const EVENT_ID_HK_ENABLED: u16 = 0x0305; +/// Event ID emitted in `TM[5,1]` when optical Earth Observation imaging is triggered (`ST[08]`). +pub const EVENT_ID_EO_CAPTURE: u16 = 0x0810; + +/// Event ID emitted in `TM[5,1]` when on-board DPU AI cloud-mask inference completes (`ST[08]`). +pub const EVENT_ID_DPU_INFERENCE: u16 = 0x0820; + +/// `ST[08]` Function ID: trigger Earth Observation optical telescope capture. +pub const FUNC_EO_OPTICAL_CAPTURE: u16 = 0x0010; + +/// `ST[08]` Function ID: run on-board DPU neural cloud-mask segmentation. +pub const FUNC_DPU_AI_INFERENCE: u16 = 0x0020; + +/// `ST[08]` Function ID: command spacecraft into `SAFE` mode (`mode = 0`). +pub const FUNC_ENTER_SAFE_MODE: u16 = 0x00FF; + /// Deterministic, zero-heap ECSS PUS spacecraft responder state machine. #[derive(Clone, Debug)] +#[allow(clippy::struct_excessive_bools)] pub struct PusResponder { /// 11-bit CCSDS Application Process ID for emitted telemetry. pub apid: u16, @@ -41,6 +61,14 @@ pub struct PusResponder { pub hk: ObcHousekeeping, /// Whether periodic `TM[3,25]` housekeeping generation is enabled. pub periodic_hk_enabled: bool, + /// Whether the `ST[11]` time-based command scheduler is enabled. + pub schedule_enabled: bool, + /// Number of time-tagged activities currently queued in `ST[11]`. + pub scheduled_count: u16, + /// Whether `ST[12]` autonomous on-board parameter limit monitoring (FDIR) is enabled. + pub monitoring_enabled: bool, + /// On-board scratchpad RAM (`Memory_ID = 1`) accessible via `ST[06]` load/dump/check. + pub scratchpad: [u8; OBC_SCRATCHPAD_LEN], } impl PusResponder { @@ -59,6 +87,10 @@ impl PusResponder { mode: 2, }, periodic_hk_enabled: false, + schedule_enabled: false, + scheduled_count: 0, + monitoring_enabled: false, + scratchpad: [0u8; OBC_SCRATCHPAD_LEN], } } @@ -189,25 +221,44 @@ impl PusResponder { count: &mut usize, max_slots: usize, ) -> Result { - match (service, subtype) { - (17, 1) => { + match service { + 3 => self.execute_st03(subtype, app_data, out_frames, out_lens, count, max_slots), + 6 => self.execute_st06(subtype, app_data, out_frames, out_lens, count, max_slots), + 8 => self.execute_st08(subtype, app_data, out_frames, out_lens, count, max_slots), + 11 => self.execute_st11(subtype, app_data, out_frames, out_lens, count, max_slots), + 12 => Ok(self.execute_st12(subtype)), + 17 if subtype == 1 => { self.emit_frame(17, 2, &[], out_frames, out_lens, count, max_slots)?; Ok(true) } - (3, 27) if app_data.len() >= 2 => { - let sid = u16::from_be_bytes([app_data[0], app_data[1]]); - if sid != ObcHousekeeping::SID { - return Ok(false); - } + _ => Ok(false), + } + } + + #[allow(clippy::too_many_arguments)] + fn execute_st03( + &mut self, + subtype: u8, + app_data: &[u8], + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result { + if app_data.len() < 2 { + return Ok(false); + } + let sid = u16::from_be_bytes([app_data[0], app_data[1]]); + if sid != ObcHousekeeping::SID { + return Ok(false); + } + match subtype { + 27 => { let payload = self.hk.to_app_data(); self.emit_frame(3, 25, &payload, out_frames, out_lens, count, max_slots)?; Ok(true) } - (3, 5) if app_data.len() >= 2 => { - let sid = u16::from_be_bytes([app_data[0], app_data[1]]); - if sid != ObcHousekeeping::SID { - return Ok(false); - } + 5 => { self.periodic_hk_enabled = true; self.push_event( 1, @@ -220,18 +271,176 @@ impl PusResponder { )?; Ok(true) } - (3, 6) if app_data.len() >= 2 => { - let sid = u16::from_be_bytes([app_data[0], app_data[1]]); - if sid != ObcHousekeeping::SID { + 6 => { + self.periodic_hk_enabled = false; + Ok(true) + } + _ => Ok(false), + } + } + + #[allow(clippy::too_many_arguments)] + fn execute_st06( + &mut self, + subtype: u8, + app_data: &[u8], + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result { + match subtype { + 2 if app_data.len() >= 5 => { + let mem_id = app_data[0]; + let addr = u32::from_be_bytes([app_data[1], app_data[2], app_data[3], app_data[4]]) + as usize; + let data = &app_data[5..]; + if mem_id != 1 || addr + data.len() > OBC_SCRATCHPAD_LEN { + return Ok(false); + } + self.scratchpad[addr..addr + data.len()].copy_from_slice(data); + Ok(true) + } + 5 if app_data.len() >= 7 => { + let mem_id = app_data[0]; + let addr = u32::from_be_bytes([app_data[1], app_data[2], app_data[3], app_data[4]]) + as usize; + let len = u16::from_be_bytes([app_data[5], app_data[6]]) as usize; + if mem_id != 1 || addr + len > OBC_SCRATCHPAD_LEN || len > 32 { + return Ok(false); + } + let mut report = [0u8; 37]; + report[..5].copy_from_slice(&app_data[..5]); + report[5..5 + len].copy_from_slice(&self.scratchpad[addr..addr + len]); + self.emit_frame( + 6, + 6, + &report[..5 + len], + out_frames, + out_lens, + count, + max_slots, + )?; + Ok(true) + } + 9 if app_data.len() >= 7 => { + let mem_id = app_data[0]; + let addr = u32::from_be_bytes([app_data[1], app_data[2], app_data[3], app_data[4]]) + as usize; + let len = u16::from_be_bytes([app_data[5], app_data[6]]) as usize; + if mem_id != 1 || addr + len > OBC_SCRATCHPAD_LEN { return Ok(false); } - self.periodic_hk_enabled = false; + let checksum = crc16_ccitt(&self.scratchpad[addr..addr + len]); + let crc_bytes = checksum.to_be_bytes(); + let mut report = [0u8; 9]; + report[..7].copy_from_slice(&app_data[..7]); + report[7] = crc_bytes[0]; + report[8] = crc_bytes[1]; + self.emit_frame(6, 10, &report, out_frames, out_lens, count, max_slots)?; Ok(true) } _ => Ok(false), } } + #[allow(clippy::too_many_arguments)] + fn execute_st08( + &mut self, + subtype: u8, + app_data: &[u8], + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result { + if subtype != 1 || app_data.len() < 2 { + return Ok(false); + } + let func_id = u16::from_be_bytes([app_data[0], app_data[1]]); + let args = &app_data[2..]; + match func_id { + FUNC_EO_OPTICAL_CAPTURE => { + self.hk.mode = 3; // EO_IMAGING + self.push_event( + 1, + EVENT_ID_EO_CAPTURE, + args, + out_frames, + out_lens, + count, + max_slots, + )?; + Ok(true) + } + FUNC_DPU_AI_INFERENCE => { + self.push_event( + 1, + EVENT_ID_DPU_INFERENCE, + args, + out_frames, + out_lens, + count, + max_slots, + )?; + Ok(true) + } + FUNC_ENTER_SAFE_MODE => { + self.hk.mode = 0; // SAFE + Ok(true) + } + _ => Ok(false), + } + } + + #[allow(clippy::too_many_arguments)] + fn execute_st11( + &mut self, + subtype: u8, + app_data: &[u8], + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result { + match subtype { + 1 => { + self.schedule_enabled = true; + Ok(true) + } + 2 => { + self.schedule_enabled = false; + Ok(true) + } + 3 => { + self.scheduled_count = 0; + Ok(true) + } + 4 if app_data.len() >= 4 => { + self.scheduled_count = self.scheduled_count.saturating_add(1); + let cnt = self.scheduled_count.to_be_bytes(); + let summary = [u8::from(self.schedule_enabled), cnt[0], cnt[1]]; + self.emit_frame(11, 13, &summary, out_frames, out_lens, count, max_slots)?; + Ok(true) + } + _ => Ok(false), + } + } + + fn execute_st12(&mut self, subtype: u8) -> bool { + match subtype { + 1 => { + self.monitoring_enabled = true; + true + } + 2 => { + self.monitoring_enabled = false; + true + } + _ => false, + } + } + fn push_tm_1_1( &mut self, request_id: u32, diff --git a/crates/xtce-pus/src/lib.rs b/crates/xtce-pus/src/lib.rs index 5fd0746..fc452c8 100644 --- a/crates/xtce-pus/src/lib.rs +++ b/crates/xtce-pus/src/lib.rs @@ -1,15 +1,17 @@ //! `#![no_std]` implementation of ECSS-E-ST-70-41C Packet Utilization Standard (PUS-C) //! over CCSDS 133.0-B Space Packets, with a deterministic Hardware-in-the-Loop (HIL) -//! On-Board Computer responder. +//! On-Board Computer responder and dual-use telecommand authentication. //! //! # Guarantees //! -//! * **`#![no_std]` and zero heap allocations.** Every parser, encoder, and HIL responder -//! method operates on caller-supplied byte slices so the crate can run unmodified on bare-metal -//! flight targets (`thumbv7em-none-eabihf` Cortex-M, RISC-V, LEON/SPARC) and ground tools. +//! * **`#![no_std]` and zero heap allocations.** Every parser, encoder, security gate, and HIL +//! responder method operates on caller-supplied byte slices so the crate can run unmodified +//! on bare-metal flight targets (`thumbv7em-none-eabihf` Cortex-M, RISC-V, LEON/SPARC) and +//! ground tools. //! * **No panics.** `unwrap`, `expect`, and `panic!` are denied across the library. -//! * **End-to-end CRC-16-CCITT protection.** Every parsed and encoded frame is checked or -//! stamped with the ECSS-E-ST-70-41C Annex B syndrome (`0x1021`, initial `0xFFFF`). +//! * **End-to-end CRC-16-CCITT and SipHash-2-4 protection.** Every frame is verified against +//! the ECSS-E-ST-70-41C Annex B syndrome (`0x1021`, initial `0xFFFF`), and critical dual-use +//! telecommands can be protected against spoofing and replay via [`TcSecurityGate`]. #![no_std] #![deny(missing_docs)] @@ -27,20 +29,28 @@ pub mod crc; pub mod hil; pub mod packet; +pub mod security; pub mod services; pub use crc::{crc16_ccitt, verify_crc16_ccitt}; pub use hil::{ ERR_CODE_CRC_MISMATCH, ERR_CODE_NOT_A_TC, ERR_CODE_UNSUPPORTED, EVENT_ID_CORRUPTED_TC, - EVENT_ID_HK_ENABLED, MAX_HIL_FRAME_LEN, PusResponder, + EVENT_ID_DPU_INFERENCE, EVENT_ID_EO_CAPTURE, EVENT_ID_HK_ENABLED, FUNC_DPU_AI_INFERENCE, + FUNC_ENTER_SAFE_MODE, FUNC_EO_OPTICAL_CAPTURE, MAX_HIL_FRAME_LEN, OBC_SCRATCHPAD_LEN, + PusResponder, }; pub use packet::{ AckFlags, CucTimestamp, PEC_LEN, PRIMARY_HEADER_LEN, PUS_VERSION_C, PusError, PusHeader, PusPacket, TC_SECONDARY_HEADER_LEN, TM_SECONDARY_HEADER_LEN, TcParams, TmParams, encode_tc, encode_tm, }; +pub use security::{ + AUTH_KEY_LEN, ERR_CODE_AUTH_FAILED, ERR_CODE_REPLAY_DETECTED, SecurityError, + TC_AUTH_TRAILER_LEN, TcSecurityGate, build_auth_trailer, compute_mac_tag, +}; pub use services::{ - EventReport, EventSeverity, HousekeepingMessage, ObcHousekeeping, PusService, TestMessage, + EventReport, EventSeverity, FunctionCall, HousekeepingMessage, MemoryMessage, + MonitoringMessage, ObcHousekeeping, PusService, ScheduleMessage, TestMessage, VerificationReport, }; @@ -79,7 +89,6 @@ mod tests { .expect("HIL processes TC[17,1]"); assert_eq!(count, 3); - // 1. TM[1,1] Acceptance Success let tm0 = PusPacket::parse(&out_frames[0][..out_lens[0]]).expect("TM[1,1]"); assert_eq!( tm0.decode_service().expect("ST[01]"), @@ -88,14 +97,12 @@ mod tests { }) ); - // 2. TM[17,2] Are-You-Alive Connection Test Report let tm1 = PusPacket::parse(&out_frames[1][..out_lens[1]]).expect("TM[17,2]"); assert_eq!( tm1.decode_service().expect("ST[17]"), PusService::Test(TestMessage::AreYouAliveReport) ); - // 3. TM[1,7] Execution Complete Success let tm2 = PusPacket::parse(&out_frames[2][..out_lens[2]]).expect("TM[1,7]"); assert_eq!( tm2.decode_service().expect("ST[01]"), @@ -144,6 +151,143 @@ mod tests { assert_eq!(decoded_hk, responder.hk); } + #[test] + fn hil_responder_loads_dumps_and_scrubs_on_board_memory_st06() { + let mut responder = PusResponder::new(0x010, 0x0001); + let mut tc_buf = [0u8; 64]; + let mut out_frames = [[0u8; MAX_HIL_FRAME_LEN]; 4]; + let mut out_lens = [0usize; 4]; + + // 1. TC[6,2] Load b"CAMILA" into memory_id=1 at offset 0x0000_0008 + let load_app = [1, 0, 0, 0, 8, b'C', b'A', b'M', b'I', b'L', b'A']; + let tc_len = encode_tc( + &TcParams { + apid: 0x010, + sequence_count: 10, + ack: AckFlags::ACCEPT_AND_COMPLETE, + service: 6, + subtype: 2, + source_id: 0x0042, + }, + &load_app, + &mut tc_buf, + ) + .expect("encodes TC[6,2]"); + let count = responder + .process_telecommand(&tc_buf[..tc_len], &mut out_frames, &mut out_lens) + .expect("TC[6,2] runs"); + assert_eq!(count, 2); // TM[1,1] + TM[1,7] + assert_eq!(&responder.scratchpad[8..14], b"CAMILA"); + + // 2. TC[6,9] Check CRC-16-CCITT over [8..14] (length = 6) + let check_app = [1, 0, 0, 0, 8, 0, 6]; + let tc_len = encode_tc( + &TcParams { + apid: 0x010, + sequence_count: 11, + ack: AckFlags::ACCEPT_AND_COMPLETE, + service: 6, + subtype: 9, + source_id: 0x0042, + }, + &check_app, + &mut tc_buf, + ) + .expect("encodes TC[6,9]"); + let count = responder + .process_telecommand(&tc_buf[..tc_len], &mut out_frames, &mut out_lens) + .expect("TC[6,9] runs"); + assert_eq!(count, 3); // TM[1,1] + TM[6,10] + TM[1,7] + + let tm_check = PusPacket::parse(&out_frames[1][..out_lens[1]]).expect("TM[6,10]"); + assert_eq!( + tm_check.decode_service().expect("ST[06]"), + PusService::Memory(MemoryMessage::CheckRawReport { + memory_id: 1, + address: 8, + length: 6, + checksum: crc16_ccitt(b"CAMILA"), + }) + ); + } + + #[test] + fn hil_responder_executes_st08_eo_imaging_and_st11_schedule() { + let mut responder = PusResponder::new(0x010, 0x0001); + let mut tc_buf = [0u8; 64]; + let mut out_frames = [[0u8; MAX_HIL_FRAME_LEN]; 4]; + let mut out_lens = [0usize; 4]; + + // TC[8,1] Function Call: FUNC_EO_OPTICAL_CAPTURE (0x0010) with target_id = 0x01 (Warsaw) + let fn_id = FUNC_EO_OPTICAL_CAPTURE.to_be_bytes(); + let fn_app = [fn_id[0], fn_id[1], 0x01]; + let tc_len = encode_tc( + &TcParams { + apid: 0x010, + sequence_count: 12, + ack: AckFlags::ACCEPT_AND_COMPLETE, + service: 8, + subtype: 1, + source_id: 0x0042, + }, + &fn_app, + &mut tc_buf, + ) + .expect("TC[8,1]"); + let count = responder + .process_telecommand(&tc_buf[..tc_len], &mut out_frames, &mut out_lens) + .expect("ST[08] runs"); + assert_eq!(count, 3); // TM[1,1] + TM[5,1] EO_CAPTURE + TM[1,7] + assert_eq!(responder.hk.mode, 3); + + // TC[11,1] Enable schedule, then TC[11,4] Insert time-tagged activity at T=600s + let enable_len = encode_tc( + &TcParams { + apid: 0x010, + sequence_count: 13, + ack: AckFlags::ACCEPT_AND_COMPLETE, + service: 11, + subtype: 1, + source_id: 0x0042, + }, + &[], + &mut tc_buf, + ) + .expect("TC[11,1]"); + responder + .process_telecommand(&tc_buf[..enable_len], &mut out_frames, &mut out_lens) + .expect("enables schedule"); + assert!(responder.schedule_enabled); + + let sched_app = [0x00, 0x00, 0x02, 0x58, 0x00, 0x20]; // release_time=600s, DPU task + let tc_ins = encode_tc( + &TcParams { + apid: 0x010, + sequence_count: 14, + ack: AckFlags::ACCEPT_AND_COMPLETE, + service: 11, + subtype: 4, + source_id: 0x0042, + }, + &sched_app, + &mut tc_buf, + ) + .expect("TC[11,4]"); + let count = responder + .process_telecommand(&tc_buf[..tc_ins], &mut out_frames, &mut out_lens) + .expect("inserts scheduled activity"); + assert_eq!(count, 3); // TM[1,1] + TM[11,13] + TM[1,7] + + let tm_sched = PusPacket::parse(&out_frames[1][..out_lens[1]]).expect("TM[11,13]"); + assert_eq!( + tm_sched.decode_service().expect("ST[11]"), + PusService::Schedule(ScheduleMessage::SummaryReport { + enabled: true, + pending_count: 1, + }) + ); + } + #[test] fn hil_responder_rejects_corrupted_crc_with_tm_1_2_and_tm_5_2() { let mut responder = PusResponder::new(0x010, 0x0001); @@ -162,7 +306,6 @@ mod tests { ) .expect("encodes TC"); - // Flip one bit in the service byte to corrupt the frame over the link tc_buf[7] ^= 0x80; let mut out_frames = [[0u8; MAX_HIL_FRAME_LEN]; 4]; diff --git a/crates/xtce-pus/src/security.rs b/crates/xtce-pus/src/security.rs new file mode 100644 index 0000000..bfa283f --- /dev/null +++ b/crates/xtce-pus/src/security.rs @@ -0,0 +1,241 @@ +//! `#![no_std]` telecommand authentication and anti-replay protection for dual-use missions. +//! +//! Modern European and Polish dual-use constellations (such as *PIAST* and *CAMILA*) require +//! uplink authentication and replay resistance to prevent unauthorized command injection or +//! capture-and-replay attacks over RF links. +//! +//! This module implements a zero-allocation, constant-time 64-bit Keyed Message Authentication +//! Code (SipHash-2-4, RFC 10130 / Aumasson & Bernstein) coupled with a strictly monotonic +//! 32-bit anti-replay counter (`TcSecurityGate`). + +/// Length of the 128-bit pre-shared spacecraft uplink authentication key in octets. +pub const AUTH_KEY_LEN: usize = 16; + +/// Length of the appended telecommand security trailer (`4-byte counter || 8-byte MAC tag`). +pub const TC_AUTH_TRAILER_LEN: usize = 12; + +/// Failure code reported when a telecommand carries an expired or replayed counter. +pub const ERR_CODE_REPLAY_DETECTED: u16 = 0x5EC1; + +/// Failure code reported when a telecommand's 64-bit authentication tag is invalid. +pub const ERR_CODE_AUTH_FAILED: u16 = 0x5EC2; + +/// Errors returned by [`TcSecurityGate`] when verifying an authenticated telecommand. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum SecurityError { + /// The application data is too short to contain the 12-byte authentication trailer. + MissingTrailer, + /// The 32-bit counter is less than or equal to the last accepted telecommand counter. + ReplayAttack { + /// Counter value received in the telecommand trailer. + received: u32, + /// Highest counter value previously accepted by the spacecraft. + last_accepted: u32, + }, + /// Constant-time MAC verification failed (invalid key or tampered payload). + InvalidMacTag, +} + +/// Computes a 64-bit SipHash-2-4 authentication tag over `counter` and `data` using `key`. +#[must_use] +pub const fn compute_mac_tag(key: &[u8; AUTH_KEY_LEN], counter: u32, data: &[u8]) -> u64 { + let k0 = u64::from_le_bytes([ + key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7], + ]); + let k1 = u64::from_le_bytes([ + key[8], key[9], key[10], key[11], key[12], key[13], key[14], key[15], + ]); + + let mut v0 = k0 ^ 0x736f_6d65_7073_6575; + let mut v1 = k1 ^ 0x646f_7261_6e64_6f6d; + let mut v2 = k0 ^ 0x6c79_6765_6e65_7261; + let mut v3 = k1 ^ 0x7465_6462_7974_6573; + + // Mix the 32-bit monotonic anti-replay counter as the first 64-bit domain word + let counter_word = (counter as u64) | 0xA5A5_0000_0000_0000; + v3 ^= counter_word; + sip_round(&mut v0, &mut v1, &mut v2, &mut v3); + sip_round(&mut v0, &mut v1, &mut v2, &mut v3); + v0 ^= counter_word; + + let len = data.len(); + let full_chunks = len / 8; + let mut i = 0usize; + while i < full_chunks { + let base = i * 8; + let m = u64::from_le_bytes([ + data[base], + data[base + 1], + data[base + 2], + data[base + 3], + data[base + 4], + data[base + 5], + data[base + 6], + data[base + 7], + ]); + v3 ^= m; + sip_round(&mut v0, &mut v1, &mut v2, &mut v3); + sip_round(&mut v0, &mut v1, &mut v2, &mut v3); + v0 ^= m; + i += 1; + } + + let mut tail = ((len & 0xFF) as u64) << 56; + let rem_start = full_chunks * 8; + let mut r = 0usize; + while rem_start + r < len { + tail |= (data[rem_start + r] as u64) << (r * 8); + r += 1; + } + + v3 ^= tail; + sip_round(&mut v0, &mut v1, &mut v2, &mut v3); + sip_round(&mut v0, &mut v1, &mut v2, &mut v3); + v0 ^= tail; + + v2 ^= 0xFF; + sip_round(&mut v0, &mut v1, &mut v2, &mut v3); + sip_round(&mut v0, &mut v1, &mut v2, &mut v3); + sip_round(&mut v0, &mut v1, &mut v2, &mut v3); + sip_round(&mut v0, &mut v1, &mut v2, &mut v3); + + v0 ^ v1 ^ v2 ^ v3 +} + +const fn sip_round(v0: &mut u64, v1: &mut u64, v2: &mut u64, v3: &mut u64) { + *v0 = v0.wrapping_add(*v1); + *v1 = v1.rotate_left(13); + *v1 ^= *v0; + *v0 = v0.rotate_left(32); + *v2 = v2.wrapping_add(*v3); + *v3 = v3.rotate_left(16); + *v3 ^= *v2; + *v0 = v0.wrapping_add(*v3); + *v3 = v3.rotate_left(21); + *v3 ^= *v0; + *v2 = v2.wrapping_add(*v1); + *v1 = v1.rotate_left(17); + *v1 ^= *v2; + *v2 = v2.rotate_left(32); +} + +/// Encodes a 12-byte authentication trailer (`4-byte big-endian counter || 8-byte big-endian MAC`). +#[must_use] +pub const fn build_auth_trailer( + key: &[u8; AUTH_KEY_LEN], + counter: u32, + app_data: &[u8], +) -> [u8; TC_AUTH_TRAILER_LEN] { + let tag = compute_mac_tag(key, counter, app_data); + let c = counter.to_be_bytes(); + let t = tag.to_be_bytes(); + [ + c[0], c[1], c[2], c[3], t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], + ] +} + +/// On-board telecommand security gate enforcing anti-replay and MAC verification. +#[derive(Clone, Debug)] +pub struct TcSecurityGate { + key: [u8; AUTH_KEY_LEN], + last_counter: u32, +} + +impl TcSecurityGate { + /// Creates a new security gate with a 128-bit pre-shared uplink key and initial counter `0`. + #[must_use] + pub const fn new(key: [u8; AUTH_KEY_LEN]) -> Self { + Self { + key, + last_counter: 0, + } + } + + /// The highest anti-replay counter accepted so far. + #[must_use] + pub const fn last_counter(&self) -> u32 { + self.last_counter + } + + /// Verifies `signed_app_data` (`payload || 12-byte trailer`), returning the authenticated + /// payload slice and advancing the anti-replay watermark on success. + /// + /// # Errors + /// + /// Returns [`SecurityError`] if the trailer is missing, the counter is replayed, or the + /// 64-bit MAC tag does not match in constant time. + pub fn verify_and_strip<'a>( + &mut self, + signed_app_data: &'a [u8], + ) -> Result<&'a [u8], SecurityError> { + if signed_app_data.len() < TC_AUTH_TRAILER_LEN { + return Err(SecurityError::MissingTrailer); + } + let split = signed_app_data.len() - TC_AUTH_TRAILER_LEN; + let payload = &signed_app_data[..split]; + let trailer = &signed_app_data[split..]; + + let counter = u32::from_be_bytes([trailer[0], trailer[1], trailer[2], trailer[3]]); + if counter <= self.last_counter { + return Err(SecurityError::ReplayAttack { + received: counter, + last_accepted: self.last_counter, + }); + } + + let expected_tag = compute_mac_tag(&self.key, counter, payload).to_be_bytes(); + let mut diff = 0u8; + let mut i = 0usize; + while i < 8 { + diff |= trailer[4 + i] ^ expected_tag[i]; + i += 1; + } + + if diff != 0 { + return Err(SecurityError::InvalidMacTag); + } + + self.last_counter = counter; + Ok(payload) + } +} + +#[cfg(test)] +mod tests { + use super::{AUTH_KEY_LEN, SecurityError, TcSecurityGate, build_auth_trailer}; + + const TEST_KEY: [u8; AUTH_KEY_LEN] = *b"POLSA_CAMILA_KEY"; + + #[test] + fn accepts_authentic_monotonic_commands_and_rejects_replay_or_tampering() { + let mut gate = TcSecurityGate::new(TEST_KEY); + let payload = [0x00, 0x10]; // Function_ID = 0x0010 + let trailer = build_auth_trailer(&TEST_KEY, 1, &payload); + + let mut signed = [0u8; 14]; + signed[..2].copy_from_slice(&payload); + signed[2..].copy_from_slice(&trailer); + + let verified = gate.verify_and_strip(&signed).expect("first TC valid"); + assert_eq!(verified, &payload); + assert_eq!(gate.last_counter(), 1); + + // Replaying the exact same frame must be rejected + assert_eq!( + gate.verify_and_strip(&signed), + Err(SecurityError::ReplayAttack { + received: 1, + last_accepted: 1, + }) + ); + + // Counter = 2 with tampered payload byte must be rejected + let trailer2 = build_auth_trailer(&TEST_KEY, 2, &payload); + signed[2..].copy_from_slice(&trailer2); + signed[1] ^= 0x01; + assert_eq!( + gate.verify_and_strip(&signed), + Err(SecurityError::InvalidMacTag) + ); + } +} diff --git a/crates/xtce-pus/src/services.rs b/crates/xtce-pus/src/services.rs index ba99634..45060f0 100644 --- a/crates/xtce-pus/src/services.rs +++ b/crates/xtce-pus/src/services.rs @@ -1,4 +1,5 @@ -//! ECSS-E-ST-70-41C service payload decoders and encoders (`ST[01]`, `ST[03]`, `ST[05]`, `ST[17]`). +//! ECSS-E-ST-70-41C service payload decoders and encoders (`ST[01]`, `ST[03]`, `ST[05]`, `ST[06]`, +//! `ST[08]`, `ST[11]`, `ST[12]`, `ST[17]`). use crate::packet::{PusError, PusPacket}; @@ -72,7 +73,7 @@ pub struct ObcHousekeeping { pub bus_voltage_mv: u16, /// OBC board temperature in centi-degrees Celsius (e.g. `2350` for 23.50 °C). pub obc_temp_cdeg: i16, - /// Operational mode (`0 = SAFE`, `1 = IDLE`, `2 = NOMINAL`, `3 = SCIENCE`). + /// Operational mode (`0 = SAFE`, `1 = IDLE`, `2 = NOMINAL`, `3 = EO_IMAGING`). pub mode: u8, } @@ -135,6 +136,110 @@ pub struct EventReport<'a> { pub aux_data: &'a [u8], } +/// ECSS Service 6 (`ST[06]`) On-Board Memory Management message. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum MemoryMessage<'a> { + /// `TC[6,2]` — Load raw data bytes into on-board memory `memory_id` at `address`. + LoadRaw { + /// Target memory partition identifier (e.g. `1 = OBC_RAM`, `2 = DPU_FLASH`). + memory_id: u8, + /// 32-bit start address. + address: u32, + /// Bytes to write. + data: &'a [u8], + }, + /// `TC[6,5]` — Request a raw memory dump from `memory_id` at `address`. + DumpRawRequest { + /// Target memory partition identifier. + memory_id: u8, + /// 32-bit start address. + address: u32, + /// Number of octets requested. + length: u16, + }, + /// `TM[6,6]` — Raw memory dump telemetry report. + DumpRawReport { + /// Source memory partition identifier. + memory_id: u8, + /// 32-bit start address. + address: u32, + /// Dumped memory octets. + data: &'a [u8], + }, + /// `TC[6,9]` — Request a CRC-16-CCITT memory integrity scrub over `[address..address+length]`. + CheckRawRequest { + /// Target memory partition identifier. + memory_id: u8, + /// 32-bit start address. + address: u32, + /// Number of octets to scrub. + length: u16, + }, + /// `TM[6,10]` — Memory integrity check report carrying the computed CRC-16-CCITT checksum. + CheckRawReport { + /// Source memory partition identifier. + memory_id: u8, + /// 32-bit start address. + address: u32, + /// Number of octets scrubbed. + length: u16, + /// Computed CRC-16-CCITT syndrome over the region. + checksum: u16, + }, +} + +/// ECSS Service 8 (`ST[08]`) Function Management telecommand. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct FunctionCall<'a> { + /// 16-bit Mission Function Identifier (`Function_ID`). + pub function_id: u16, + /// Raw argument bytes passed to the on-board function. + pub args: &'a [u8], +} + +/// ECSS Service 11 (`ST[11]`) Time-Based Scheduling message. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum ScheduleMessage<'a> { + /// `TC[11,1]` — Enable execution of time-tagged on-board schedule activities. + Enable, + /// `TC[11,2]` — Disable execution of time-tagged on-board schedule activities. + Disable, + /// `TC[11,3]` — Reset (clear) all queued activities in the on-board command schedule. + Reset, + /// `TC[11,4]` — Insert a time-tagged activity into the on-board schedule. + InsertActivity { + /// Spacecraft CUC coarse release time (seconds) when the activity shall execute. + release_time_s: u32, + /// Encoded telecommand or action payload to release at `release_time_s`. + activity_data: &'a [u8], + }, + /// `TM[11,13]` — Schedule summary status report. + SummaryReport { + /// Whether the time-based scheduler is currently enabled. + enabled: bool, + /// Number of pending time-tagged activities waiting in the queue. + pending_count: u16, + }, +} + +/// ECSS Service 12 (`ST[12]`) On-Board Monitoring (FDIR) message. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum MonitoringMessage { + /// `TC[12,1]` — Enable autonomous on-board parameter limit monitoring (FDIR). + Enable, + /// `TC[12,2]` — Disable autonomous on-board parameter limit monitoring. + Disable, + /// `TM[12,12]` — Check transition report emitted when a monitored parameter crosses a limit. + CheckTransitionReport { + /// Monitored parameter identifier (`Param_ID`). + param_id: u16, + /// Observed parameter value that triggered the transition. + observed_value: i32, + /// Limit threshold that was crossed. + limit_value: i32, + }, +} + /// ECSS Service 17 (`ST[17]`) Test service message. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum TestMessage { @@ -153,6 +258,14 @@ pub enum PusService<'a> { Housekeeping(HousekeepingMessage<'a>), /// `ST[05]` Event Report. Event(EventReport<'a>), + /// `ST[06]` On-Board Memory Management message. + Memory(MemoryMessage<'a>), + /// `ST[08]` Function Management call (`TC[8,1]`). + Function(FunctionCall<'a>), + /// `ST[11]` Time-Based Scheduling message. + Schedule(ScheduleMessage<'a>), + /// `ST[12]` On-Board Monitoring (FDIR) message. + Monitoring(MonitoringMessage), /// `ST[17]` Test service message. Test(TestMessage), /// Any other service/subtype pair with its raw application data slice. @@ -178,10 +291,39 @@ impl<'a> PusPacket<'a> { let subtype = self.header.subtype(); let data = self.app_data; - match (self.header.is_telecommand(), service, subtype) { - (false, 1, 1 | 3 | 7) => { + match service { + 1 => Self::decode_st01(self.header.is_telecommand(), subtype, data), + 3 => Self::decode_st03(self.header.is_telecommand(), subtype, data), + 5 => Self::decode_st05(self.header.is_telecommand(), subtype, data), + 6 => Self::decode_st06(self.header.is_telecommand(), subtype, data), + 8 => Self::decode_st08(self.header.is_telecommand(), subtype, data), + 11 => Self::decode_st11(self.header.is_telecommand(), subtype, data), + 12 => Self::decode_st12(self.header.is_telecommand(), subtype, data), + 17 => match (self.header.is_telecommand(), subtype) { + (true, 1) => Ok(PusService::Test(TestMessage::AreYouAliveCommand)), + (false, 2) => Ok(PusService::Test(TestMessage::AreYouAliveReport)), + _ => Ok(PusService::Custom { + service, + subtype, + app_data: data, + }), + }, + _ => Ok(PusService::Custom { + service, + subtype, + app_data: data, + }), + } + } + + fn decode_st01(is_tc: bool, subtype: u8, data: &'a [u8]) -> Result, PusError> { + match (is_tc, subtype) { + (false, 1 | 3 | 7) => { if data.len() < 4 { - return Err(PusError::MalformedServiceData { service, subtype }); + return Err(PusError::MalformedServiceData { + service: 1, + subtype, + }); } let request_id = u32::from_be_bytes([data[0], data[1], data[2], data[3]]); let report = match subtype { @@ -191,9 +333,12 @@ impl<'a> PusPacket<'a> { }; Ok(PusService::Verification(report)) } - (false, 1, 2 | 8) => { + (false, 2 | 8) => { if data.len() < 6 { - return Err(PusError::MalformedServiceData { service, subtype }); + return Err(PusError::MalformedServiceData { + service: 1, + subtype, + }); } let request_id = u32::from_be_bytes([data[0], data[1], data[2], data[3]]); let failure_code = u16::from_be_bytes([data[4], data[5]]); @@ -210,9 +355,22 @@ impl<'a> PusPacket<'a> { }; Ok(PusService::Verification(report)) } - (true, 3, 5 | 6 | 27) => { + _ => Ok(PusService::Custom { + service: 1, + subtype, + app_data: data, + }), + } + } + + fn decode_st03(is_tc: bool, subtype: u8, data: &'a [u8]) -> Result, PusError> { + match (is_tc, subtype) { + (true, 5 | 6 | 27) => { if data.len() < 2 { - return Err(PusError::MalformedServiceData { service, subtype }); + return Err(PusError::MalformedServiceData { + service: 3, + subtype, + }); } let sid = u16::from_be_bytes([data[0], data[1]]); let msg = match subtype { @@ -222,9 +380,12 @@ impl<'a> PusPacket<'a> { }; Ok(PusService::Housekeeping(msg)) } - (false, 3, 25) => { + (false, 25) => { if data.len() < 2 { - return Err(PusError::MalformedServiceData { service, subtype }); + return Err(PusError::MalformedServiceData { + service: 3, + subtype, + }); } let sid = u16::from_be_bytes([data[0], data[1]]); Ok(PusService::Housekeeping( @@ -234,27 +395,204 @@ impl<'a> PusPacket<'a> { }, )) } - (false, 5, 1..=4) => { - if data.len() < 2 { - return Err(PusError::MalformedServiceData { service, subtype }); + _ => Ok(PusService::Custom { + service: 3, + subtype, + app_data: data, + }), + } + } + + fn decode_st05(is_tc: bool, subtype: u8, data: &'a [u8]) -> Result, PusError> { + if is_tc || !(1..=4).contains(&subtype) { + return Ok(PusService::Custom { + service: 5, + subtype, + app_data: data, + }); + } + if data.len() < 2 { + return Err(PusError::MalformedServiceData { + service: 5, + subtype, + }); + } + let severity = match subtype { + 1 => EventSeverity::Informative, + 2 => EventSeverity::LowAnomaly, + 3 => EventSeverity::MediumAnomaly, + _ => EventSeverity::HighAnomaly, + }; + let event_id = u16::from_be_bytes([data[0], data[1]]); + Ok(PusService::Event(EventReport { + severity, + event_id, + aux_data: &data[2..], + })) + } + + fn decode_st06(is_tc: bool, subtype: u8, data: &'a [u8]) -> Result, PusError> { + match (is_tc, subtype) { + (true, 2) | (false, 6) => { + if data.len() < 5 { + return Err(PusError::MalformedServiceData { + service: 6, + subtype, + }); + } + let memory_id = data[0]; + let address = u32::from_be_bytes([data[1], data[2], data[3], data[4]]); + let msg = if is_tc { + MemoryMessage::LoadRaw { + memory_id, + address, + data: &data[5..], + } + } else { + MemoryMessage::DumpRawReport { + memory_id, + address, + data: &data[5..], + } + }; + Ok(PusService::Memory(msg)) + } + (true, 5 | 9) => { + if data.len() < 7 { + return Err(PusError::MalformedServiceData { + service: 6, + subtype, + }); } - let severity = match subtype { - 1 => EventSeverity::Informative, - 2 => EventSeverity::LowAnomaly, - 3 => EventSeverity::MediumAnomaly, - _ => EventSeverity::HighAnomaly, + let memory_id = data[0]; + let address = u32::from_be_bytes([data[1], data[2], data[3], data[4]]); + let length = u16::from_be_bytes([data[5], data[6]]); + let msg = if subtype == 5 { + MemoryMessage::DumpRawRequest { + memory_id, + address, + length, + } + } else { + MemoryMessage::CheckRawRequest { + memory_id, + address, + length, + } }; - let event_id = u16::from_be_bytes([data[0], data[1]]); - Ok(PusService::Event(EventReport { - severity, - event_id, - aux_data: &data[2..], + Ok(PusService::Memory(msg)) + } + (false, 10) => { + if data.len() < 9 { + return Err(PusError::MalformedServiceData { + service: 6, + subtype, + }); + } + let memory_id = data[0]; + let address = u32::from_be_bytes([data[1], data[2], data[3], data[4]]); + let length = u16::from_be_bytes([data[5], data[6]]); + let checksum = u16::from_be_bytes([data[7], data[8]]); + Ok(PusService::Memory(MemoryMessage::CheckRawReport { + memory_id, + address, + length, + checksum, })) } - (true, 17, 1) => Ok(PusService::Test(TestMessage::AreYouAliveCommand)), - (false, 17, 2) => Ok(PusService::Test(TestMessage::AreYouAliveReport)), _ => Ok(PusService::Custom { - service, + service: 6, + subtype, + app_data: data, + }), + } + } + + fn decode_st08(is_tc: bool, subtype: u8, data: &'a [u8]) -> Result, PusError> { + if !is_tc || subtype != 1 { + return Ok(PusService::Custom { + service: 8, + subtype, + app_data: data, + }); + } + if data.len() < 2 { + return Err(PusError::MalformedServiceData { + service: 8, + subtype, + }); + } + let function_id = u16::from_be_bytes([data[0], data[1]]); + Ok(PusService::Function(FunctionCall { + function_id, + args: &data[2..], + })) + } + + fn decode_st11(is_tc: bool, subtype: u8, data: &'a [u8]) -> Result, PusError> { + match (is_tc, subtype) { + (true, 1) => Ok(PusService::Schedule(ScheduleMessage::Enable)), + (true, 2) => Ok(PusService::Schedule(ScheduleMessage::Disable)), + (true, 3) => Ok(PusService::Schedule(ScheduleMessage::Reset)), + (true, 4) => { + if data.len() < 4 { + return Err(PusError::MalformedServiceData { + service: 11, + subtype, + }); + } + let release_time_s = u32::from_be_bytes([data[0], data[1], data[2], data[3]]); + Ok(PusService::Schedule(ScheduleMessage::InsertActivity { + release_time_s, + activity_data: &data[4..], + })) + } + (false, 13) => { + if data.len() < 3 { + return Err(PusError::MalformedServiceData { + service: 11, + subtype, + }); + } + let enabled = data[0] != 0; + let pending_count = u16::from_be_bytes([data[1], data[2]]); + Ok(PusService::Schedule(ScheduleMessage::SummaryReport { + enabled, + pending_count, + })) + } + _ => Ok(PusService::Custom { + service: 11, + subtype, + app_data: data, + }), + } + } + + fn decode_st12(is_tc: bool, subtype: u8, data: &'a [u8]) -> Result, PusError> { + match (is_tc, subtype) { + (true, 1) => Ok(PusService::Monitoring(MonitoringMessage::Enable)), + (true, 2) => Ok(PusService::Monitoring(MonitoringMessage::Disable)), + (false, 12) => { + if data.len() < 10 { + return Err(PusError::MalformedServiceData { + service: 12, + subtype, + }); + } + let param_id = u16::from_be_bytes([data[0], data[1]]); + let observed_value = i32::from_be_bytes([data[2], data[3], data[4], data[5]]); + let limit_value = i32::from_be_bytes([data[6], data[7], data[8], data[9]]); + Ok(PusService::Monitoring( + MonitoringMessage::CheckTransitionReport { + param_id, + observed_value, + limit_value, + }, + )) + } + _ => Ok(PusService::Custom { + service: 12, subtype, app_data: data, }), From c6f6ae5521657fc99baaa39e755c31619e8870eb Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Thu, 19 Nov 2026 00:08:13 +0100 Subject: [PATCH 10/13] feat(cli,pus): add xtce encode command, live UDP HIL server, ST[20], and PyPI workflow (v0.2.0) Add 'xtce encode' to assemble binary CCSDS telemetry or telecommand packets from an XTCE definition and NAME=VALUE assignments, automatically populating FixedValueEntry bits, inheritance RestrictionCriteria, and ArgumentAssignments. Add 'xtce pus --hil-udp ' to expose the no_std PusResponder over a live UDP socket for closed-loop FlatSat testing. Add ECSS Service ST[20] On-Board Parameter Management (TC[20,1], TM[20,2], TC[20,3]) to xtce-pus, add a multi-platform maturin PyPI wheel workflow (.github/workflows/pypi.yml), and bump workspace version to 0.2.0. --- .github/workflows/pypi.yml | 56 +++ Cargo.lock | 14 +- Cargo.toml | 10 +- crates/xtce-cli/README.md | 8 +- crates/xtce-cli/src/encode.rs | 625 ++++++++++++++++++++++++++++++++ crates/xtce-cli/src/main.rs | 76 ++++ crates/xtce-cli/src/pus.rs | 147 +++++++- crates/xtce-pus/README.md | 1 + crates/xtce-pus/src/hil.rs | 48 +++ crates/xtce-pus/src/lib.rs | 6 +- crates/xtce-pus/src/services.rs | 65 ++++ 11 files changed, 1035 insertions(+), 21 deletions(-) create mode 100644 .github/workflows/pypi.yml create mode 100644 crates/xtce-cli/src/encode.rs diff --git a/.github/workflows/pypi.yml b/.github/workflows/pypi.yml new file mode 100644 index 0000000..27df2e9 --- /dev/null +++ b/.github/workflows/pypi.yml @@ -0,0 +1,56 @@ +name: Python Wheels (PyPI) + +on: + release: + types: [published] + push: + tags: ["v*"] + workflow_dispatch: + +jobs: + build-wheels: + name: wheel (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-14, windows-latest] + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - uses: Swatinem/rust-cache@v2 + - name: Build Python wheel with maturin + run: | + pip install maturin + maturin build --release --out dist --manifest-path crates/xtce-py/Cargo.toml + - uses: actions/upload-artifact@v4 + with: + name: wheels-${{ matrix.os }} + path: dist/*.whl + + publish-pypi: + name: publish to PyPI + needs: build-wheels + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v4 + with: + pattern: wheels-* + path: dist + merge-multiple: true + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Publish wheels to PyPI + env: + MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }} + run: | + if [ -z "$MATURIN_PYPI_TOKEN" ]; then + echo "::notice::PYPI_API_TOKEN is not set; wheels are built and uploaded as workflow artifacts" + exit 0 + fi + pip install maturin + maturin upload dist/*.whl diff --git a/Cargo.lock b/Cargo.lock index ac4f646..72b468d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -915,7 +915,7 @@ checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" [[package]] name = "xtask" -version = "0.1.3" +version = "0.2.0" dependencies = [ "clap", "serde_json", @@ -925,7 +925,7 @@ dependencies = [ [[package]] name = "xtce-cli" -version = "0.1.3" +version = "0.2.0" dependencies = [ "clap", "xtce-codegen", @@ -936,7 +936,7 @@ dependencies = [ [[package]] name = "xtce-codegen" -version = "0.1.3" +version = "0.2.0" dependencies = [ "criterion", "prettyplease", @@ -950,7 +950,7 @@ dependencies = [ [[package]] name = "xtce-codegen-e2e" -version = "0.1.3" +version = "0.2.0" dependencies = [ "xtce-codegen", "xtce-decode", @@ -959,7 +959,7 @@ dependencies = [ [[package]] name = "xtce-decode" -version = "0.1.3" +version = "0.2.0" dependencies = [ "criterion", "proptest", @@ -969,7 +969,7 @@ dependencies = [ [[package]] name = "xtce-model" -version = "0.1.3" +version = "0.2.0" dependencies = [ "criterion", "proptest", @@ -979,7 +979,7 @@ dependencies = [ [[package]] name = "xtce-pus" -version = "0.1.3" +version = "0.2.0" [[package]] name = "zerocopy" diff --git a/Cargo.toml b/Cargo.toml index ca4fa12..6e9a93f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ members = ["crates/*", "xtask"] exclude = ["crates/xtce-py"] [workspace.package] -version = "0.1.3" +version = "0.2.0" edition = "2024" rust-version = "1.85" license = "MIT OR Apache-2.0" @@ -15,10 +15,10 @@ repository = "https://github.com/RustSpaceLab/xtce-rs" authors = ["Maciej Myszkiewicz"] [workspace.dependencies] -xtce-model = { path = "crates/xtce-model", version = "0.1.3" } -xtce-decode = { path = "crates/xtce-decode", version = "0.1.3" } -xtce-codegen = { path = "crates/xtce-codegen", version = "0.1.3" } -xtce-pus = { path = "crates/xtce-pus", version = "0.1.3" } +xtce-model = { path = "crates/xtce-model", version = "0.2.0" } +xtce-decode = { path = "crates/xtce-decode", version = "0.2.0" } +xtce-codegen = { path = "crates/xtce-codegen", version = "0.2.0" } +xtce-pus = { path = "crates/xtce-pus", version = "0.2.0" } # Keep this list short and justified — see CONTRIBUTING.md rule 7. anyhow = "1" diff --git a/crates/xtce-cli/README.md b/crates/xtce-cli/README.md index 8087a31..1266ee6 100644 --- a/crates/xtce-cli/README.md +++ b/crates/xtce-cli/README.md @@ -31,8 +31,14 @@ $ xtce wireshark mission.xml --udp-port 5005 -o mission.lua $ xtce pcap downlink.dat -o downlink.pcap $ wireshark -X lua_script:mission.lua downlink.pcap -# 5. Inspect ECSS-E-ST-70-41C (PUS-C) frames, run an EO HIL session, or emit a PUS XTCE database +# 5. Assemble a binary CCSDS telemetry or telecommand packet from an XTCE definition +$ xtce encode ecss_pus.xml TM_3_25_ObcHousekeeping \ + --set CCSDS_SEC_HDR=1 --set CCSDS_APID=0x010 --set PUS_VERSION=2 \ + --set HK_SID=1 --set OBC_UPTIME_S=3600 --set OBC_MODE=EO_IMAGING --crc --hex + +# 6. Inspect ECSS-E-ST-70-41C (PUS-C) frames, run a live UDP HIL OBC server, or emit XTCE XML $ xtce pus --hil-demo -o hil_session.bin +$ xtce pus --hil-udp 127.0.0.1:5006 $ xtce pus --emit-xtce -o ecss_pus.xml $ xtce decode ecss_pus.xml hil_session.bin --format table ``` diff --git a/crates/xtce-cli/src/encode.rs b/crates/xtce-cli/src/encode.rs new file mode 100644 index 0000000..5f69261 --- /dev/null +++ b/crates/xtce-cli/src/encode.rs @@ -0,0 +1,625 @@ +//! `xtce encode` — assemble a binary CCSDS telemetry or telecommand packet from an XTCE +//! definition and `NAME=VALUE` field assignments. +//! +//! Turns `xtce` into a bidirectional EGSE tool: given a concrete container or `` +//! name, the encoder walks the inheritance tree from the root container, populates all +//! `` bit patterns, restriction criteria (``), and command +//! `` guards automatically, applies user-supplied `--set NAME=VALUE` +//! overrides, and outputs the bit-packed packet as raw bytes or hex. + +#![allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + +use std::io::Write; +use std::path::Path; + +use xtce_codegen::{ContainerPlan, Criterion, Field, Guard, GuardTest, Node, Plan, Repr}; +use xtce_model::{IntegerCoding, XtceDb}; +use xtce_pus::crc16_ccitt; + +/// Configuration for `xtce encode`. +pub struct Options<'a> { + pub target: &'a str, + pub root: Option<&'a str>, + pub assignments: &'a [String], + pub out: Option<&'a Path>, + pub hex: bool, + pub crc: bool, +} + +/// Encodes a single packet for `target` (a container name or `` name) in `db`. +/// +/// # Errors +/// +/// Returns a descriptive error if the target container or command does not exist, if the +/// target container is abstract, if a `--set` entry is not `NAME=VALUE` or names an unknown +/// field, or if a value cannot be parsed for its XTCE type. +pub fn encode_packet( + db: &XtceDb, + target: &str, + explicit_root: Option<&str>, + assignments: &[String], + stamp_crc: bool, +) -> Result, Box> { + let container_id = resolve_target_container(db, target)?; + let container_name = db + .container(container_id) + .map(|c| db.name(c.name)) + .ok_or("internal: resolved container id does not exist")?; + + let root_name = match explicit_root { + Some(name) => name, + None => find_hierarchy_root_name(db, container_id)?, + }; + + let plan = xtce_codegen::plan( + db, + &xtce_codegen::Options { + root: Some(root_name.to_owned()), + source_label: None, + }, + )?; + + let container_plan = plan + .containers + .iter() + .find(|c| c.xtce_name == container_name) + .ok_or_else(|| { + format!("container {container_name:?} is abstract and cannot be encoded directly") + })?; + + let total_bits = container_plan.bit_length.ok_or_else(|| { + format!( + "container {container_name:?} has a variable-width field and requires fixed bit layout" + ) + })?; + + let mut buf = vec![0u8; total_bits.div_ceil(8)]; + + // 1. Populate `` bit patterns from telecommand containers. + for fixed in &container_plan.fixed { + write_fixed_bits(&mut buf, fixed.bit_offset, fixed.bit_width, &fixed.value); + } + + // 2. Populate inheritance guards (`RestrictionCriteria` and ``). + apply_inheritance_guards(&plan, &container_plan.xtce_name, &mut buf); + + // 3. Apply explicit user `--set NAME=VALUE` assignments. + for spec in assignments { + apply_single_assignment(&mut buf, container_plan, spec)?; + } + + // 4. Stamp trailing 16-bit ECSS CRC-16-CCITT if requested and packet is at least 2 bytes. + if stamp_crc && buf.len() >= 2 { + let body_end = buf.len() - 2; + let crc = crc16_ccitt(&buf[..body_end]); + buf[body_end..].copy_from_slice(&crc.to_be_bytes()); + } + + Ok(buf) +} + +fn apply_single_assignment( + buf: &mut [u8], + container_plan: &ContainerPlan, + spec: &str, +) -> Result<(), Box> { + let (name, val_str) = spec + .split_once('=') + .ok_or("invalid assignment: expected NAME=VALUE")?; + let field = container_plan + .fields + .iter() + .find(|f| f.xtce_name == name) + .ok_or("container has no field with the specified name")?; + encode_field_value(buf, field, val_str) +} + +fn resolve_target_container( + db: &XtceDb, + target: &str, +) -> Result> { + if let Some(id) = db.find_container(target) { + return Ok(id); + } + for cmd in db.meta_commands() { + if db.name(cmd.name) == target { + if let Some(cid) = cmd.container { + return Ok(cid); + } + } + } + Err(format!("no container or telecommand named {target:?} in definition").into()) +} + +fn find_hierarchy_root_name( + db: &XtceDb, + mut current: xtce_model::ContainerId, +) -> Result<&str, Box> { + let mut steps = 0usize; + while let Some(c) = db.container(current) { + if let Some(base) = c.base { + current = base; + steps += 1; + if steps > 64 { + break; + } + } else { + return Ok(db.name(c.name)); + } + } + Err("could not resolve hierarchy root container".into()) +} + +fn apply_inheritance_guards(plan: &Plan, target_name: &str, buf: &mut [u8]) { + let mut guards: Vec<&Guard> = Vec::new(); + collect_path_guards(&plan.root, target_name, &mut guards); + for guard in guards { + if let Some(val) = guard.test.sole_value() { + let bits = (val as u128) as u64; + write_bits_uint( + buf, + guard.bit_offset, + guard.bit_width, + bits, + guard.swap_bytes, + ); + } + } +} + +fn collect_path_guards<'a>(node: &'a Node, target_name: &str, out: &mut Vec<&'a Guard>) -> bool { + if node.xtce_name == target_name { + return true; + } + for (criterion, child) in &node.children { + let saved_len = out.len(); + collect_criterion_guards(criterion, out); + if collect_path_guards(child, target_name, out) { + return true; + } + out.truncate(saved_len); + } + false +} + +fn collect_criterion_guards<'a>(criterion: &'a Criterion, out: &mut Vec<&'a Guard>) { + match criterion { + Criterion::Test(guard) => { + if matches!( + guard.test, + GuardTest::Value { .. } | GuardTest::Labels { .. } + ) { + out.push(guard); + } + } + Criterion::All(children) => { + for child in children { + collect_criterion_guards(child, out); + } + } + Criterion::Any(children) => { + if let Some(first) = children.first() { + collect_criterion_guards(first, out); + } + } + } +} + +fn encode_field_value( + buf: &mut [u8], + field: &Field, + val_str: &str, +) -> Result<(), Box> { + let (bit_offset, bit_width) = field.static_span().ok_or_else(|| { + format!( + "field {:?} does not have a static bit offset", + field.xtce_name + ) + })?; + + match &field.repr { + Repr::Unsigned => { + let v = parse_uint(val_str).map_err(|e| format!("{}: {e}", field.xtce_name))?; + write_bits_uint(buf, bit_offset, bit_width, v, field.swap_bytes); + } + Repr::Signed(coding) => { + let v = parse_int(val_str).map_err(|e| format!("{}: {e}", field.xtce_name))?; + let encoded = encode_signed_bits(v, bit_width, *coding); + write_bits_uint(buf, bit_offset, bit_width, encoded, field.swap_bytes); + } + Repr::Bool => { + let b = match val_str { + "true" | "1" | "TRUE" => 1u64, + "false" | "0" | "FALSE" => 0u64, + _ => { + return Err( + format!("{}: expected boolean (true/false/1/0)", field.xtce_name).into(), + ); + } + }; + write_bits_uint(buf, bit_offset, bit_width, b, field.swap_bytes); + } + Repr::Enumerated(entries) => { + let raw = resolve_enum_value(entries, val_str, &field.xtce_name)?; + write_bits_uint( + buf, + bit_offset, + bit_width, + (raw as u128) as u64, + field.swap_bytes, + ); + } + Repr::Float32 => { + let f: f32 = val_str + .parse() + .map_err(|e| format!("{}: invalid f32 ({e})", field.xtce_name))?; + write_bits_uint( + buf, + bit_offset, + bit_width, + u64::from(f.to_bits()), + field.swap_bytes, + ); + } + Repr::Float64 => { + let f: f64 = val_str + .parse() + .map_err(|e| format!("{}: invalid f64 ({e})", field.xtce_name))?; + write_bits_uint(buf, bit_offset, bit_width, f.to_bits(), field.swap_bytes); + } + Repr::Text { .. } => { + write_raw_bytes_at_bit(buf, bit_offset, bit_width, val_str.as_bytes()); + } + Repr::Binary => { + let bytes = + parse_hex_bytes(val_str).map_err(|e| format!("{}: {e}", field.xtce_name))?; + write_raw_bytes_at_bit(buf, bit_offset, bit_width, &bytes); + } + Repr::Float16 | Repr::Mil1750a => { + let v = parse_uint(val_str).map_err(|e| format!("{}: {e}", field.xtce_name))?; + write_bits_uint(buf, bit_offset, bit_width, v, field.swap_bytes); + } + } + + Ok(()) +} + +fn resolve_enum_value( + entries: &[(i128, i128, String)], + val_str: &str, + field_name: &str, +) -> Result> { + for (low, _, label) in entries { + if label == val_str { + return Ok(*low); + } + } + if let Ok(raw) = val_str.parse::() { + for (low, high, _) in entries { + if raw >= *low && raw <= *high { + return Ok(raw); + } + } + } + Err(format!("{field_name}: {val_str:?} is not a valid enumeration label or raw value").into()) +} + +fn parse_uint(text: &str) -> Result { + if let Some(hex) = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) { + u64::from_str_radix(hex, 16) + } else { + text.parse::() + } +} + +fn parse_int(text: &str) -> Result { + if let Some(hex) = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) { + i64::from_str_radix(hex, 16) + } else { + text.parse::() + } +} + +fn parse_hex_bytes(text: &str) -> Result, &'static str> { + let clean = text + .strip_prefix("0x") + .or_else(|| text.strip_prefix("0X")) + .unwrap_or(text); + if clean.len() % 2 != 0 { + return Err("hex string must have an even number of digits"); + } + let mut out = Vec::with_capacity(clean.len() / 2); + let bytes = clean.as_bytes(); + let mut i = 0usize; + while i < bytes.len() { + let pair = std::str::from_utf8(&bytes[i..i + 2]).map_err(|_| "invalid UTF-8 in hex")?; + let b = u8::from_str_radix(pair, 16).map_err(|_| "invalid hexadecimal digit")?; + out.push(b); + i += 2; + } + Ok(out) +} + +fn encode_signed_bits(value: i64, width: u32, coding: IntegerCoding) -> u64 { + if width == 0 || width > 64 { + return 0; + } + let mask = if width == 64 { + u64::MAX + } else { + (1u64 << width) - 1 + }; + match coding { + IntegerCoding::Unsigned | IntegerCoding::TwosComplement => (value as u64) & mask, + IntegerCoding::OnesComplement => { + if value >= 0 { + (value as u64) & mask + } else { + (!(-value as u64)) & mask + } + } + IntegerCoding::SignMagnitude => { + if value >= 0 { + (value as u64) & mask + } else { + let sign_bit = 1u64 << (width - 1); + let mag_mask = sign_bit - 1; + sign_bit | ((-value as u64) & mag_mask) + } + } + } +} + +fn write_bits_uint(buf: &mut [u8], bit_offset: usize, bit_width: u32, raw: u64, swap_bytes: bool) { + if bit_width == 0 || bit_width > 64 { + return; + } + let val = if swap_bytes && bit_width >= 16 && (bit_width % 8 == 0) { + let nbytes = (bit_width / 8) as usize; + let be = raw.to_be_bytes(); + let start = 8 - nbytes; + let mut swapped = [0u8; 8]; + let mut i = 0; + while i < nbytes { + swapped[start + i] = be[7 - i]; + i += 1; + } + u64::from_be_bytes(swapped) + } else { + raw + }; + + for i in 0..(bit_width as usize) { + let shift = (bit_width as usize) - 1 - i; + let bit = ((val >> shift) & 1) as u8; + let pos = bit_offset + i; + let byte_idx = pos / 8; + let bit_in_byte = 7 - (pos % 8); + if let Some(slot) = buf.get_mut(byte_idx) { + *slot = (*slot & !(1 << bit_in_byte)) | (bit << bit_in_byte); + } + } +} + +fn write_fixed_bits(buf: &mut [u8], bit_offset: usize, bit_width: u32, right_aligned_bytes: &[u8]) { + let total_avail = right_aligned_bytes.len() * 8; + let width = bit_width as usize; + if width > total_avail { + return; + } + let start_bit_in_src = total_avail - width; + for i in 0..width { + let src_pos = start_bit_in_src + i; + let src_byte = right_aligned_bytes[src_pos / 8]; + let bit = (src_byte >> (7 - (src_pos % 8))) & 1; + let dst_pos = bit_offset + i; + let dst_idx = dst_pos / 8; + let dst_bit = 7 - (dst_pos % 8); + if let Some(slot) = buf.get_mut(dst_idx) { + *slot = (*slot & !(1 << dst_bit)) | (bit << dst_bit); + } + } +} + +fn write_raw_bytes_at_bit(buf: &mut [u8], bit_offset: usize, bit_width: u32, src: &[u8]) { + let max_bits = (bit_width as usize).min(src.len() * 8); + for i in 0..max_bits { + let src_byte = src[i / 8]; + let bit = (src_byte >> (7 - (i % 8))) & 1; + let dst_pos = bit_offset + i; + let dst_idx = dst_pos / 8; + let dst_bit = 7 - (dst_pos % 8); + if let Some(slot) = buf.get_mut(dst_idx) { + *slot = (*slot & !(1 << dst_bit)) | (bit << dst_bit); + } + } +} + +/// Executes `xtce encode` using a pre-loaded [`XtceDb`]. +/// +/// # Errors +/// +/// Returns an error if packet assembly or output writing fails. +pub fn run_with_db(db: &XtceDb, options: &Options<'_>) -> Result<(), Box> { + let bytes = encode_packet( + db, + options.target, + options.root, + options.assignments, + options.crc, + )?; + + match options.out { + Some(path) if path.as_os_str() != "-" => { + if options.hex { + let mut file = std::fs::File::create(path)?; + write_hex_line(&mut file, &bytes)?; + } else { + std::fs::write(path, &bytes)?; + } + eprintln!( + "encoded {} ({} bytes) to {}", + options.target, + bytes.len(), + path.display() + ); + } + _ => { + let stdout = std::io::stdout(); + let mut out = std::io::BufWriter::new(stdout.lock()); + if options.hex { + write_hex_line(&mut out, &bytes)?; + } else { + out.write_all(&bytes)?; + } + out.flush()?; + } + } + + Ok(()) +} + +fn write_hex_line(out: &mut impl Write, bytes: &[u8]) -> std::io::Result<()> { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut line = Vec::with_capacity(bytes.len() * 2 + 1); + for &b in bytes { + line.push(HEX[(b >> 4) as usize]); + line.push(HEX[(b & 0x0F) as usize]); + } + line.push(b'\n'); + out.write_all(&line) +} + +#[cfg(test)] +mod tests { + use xtce_decode::{Decoder, EngValue, RawValue}; + use xtce_model::XtceDb; + use xtce_pus::verify_crc16_ccitt; + + use super::encode_packet; + use crate::pus::ECSS_PUS_XTCE_XML; + + #[test] + fn encodes_container_with_guards_enums_and_crc_and_roundtrips_through_decoder() { + let db = XtceDb::from_xml(ECSS_PUS_XTCE_XML).expect("PUS XTCE loads"); + let decoder = Decoder::new(&db).expect("decoder"); + + let assignments = vec![ + "CCSDS_SEC_HDR=1".to_owned(), + "CCSDS_APID=0x010".to_owned(), + "CCSDS_SEQ_FLAGS=3".to_owned(), + "CCSDS_SEQ_COUNT=42".to_owned(), + "PUS_VERSION=2".to_owned(), + "HK_SID=1".to_owned(), + "OBC_UPTIME_S=120".to_owned(), + "OBC_VBUS_V=28200".to_owned(), + "OBC_TEMP_C=-1500".to_owned(), + "OBC_MODE=EO_IMAGING".to_owned(), + ]; + + let encoded = encode_packet(&db, "TM_3_25_ObcHousekeeping", None, &assignments, true) + .expect("encodes TM_3_25_ObcHousekeeping"); + + // Verify trailing CRC-16-CCITT is valid + assert!(verify_crc16_ccitt(&encoded)); + + // Decode back through xtce_decode::Decoder and verify round-trip values! + let packet = decoder.decode(&encoded).expect("decodes back"); + assert_eq!( + db.name(db.container(packet.container()).unwrap().name), + "TM_3_25_ObcHousekeeping" + ); + assert_eq!( + packet.get_by_name("PUS_SERVICE").unwrap().raw, + RawValue::Unsigned(3) + ); + assert_eq!( + packet.get_by_name("PUS_SUBTYPE").unwrap().raw, + RawValue::Unsigned(25) + ); + assert_eq!( + packet.get_by_name("OBC_UPTIME_S").unwrap().raw, + RawValue::Unsigned(120) + ); + assert_eq!( + packet.get_by_name("OBC_TEMP_C").unwrap().raw, + RawValue::Signed(-1500) + ); + assert_eq!( + packet.get_by_name("OBC_MODE").unwrap().eng, + EngValue::Label("EO_IMAGING") + ); + } + + #[test] + fn encodes_metacommand_with_fixed_values_and_argument_assignments() { + const CMD_XTCE: &str = r#" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +"#; + + let db = XtceDb::from_xml(CMD_XTCE).expect("loads command xml"); + let bytes = encode_packet( + &db, + "SetExposure", + None, + &["EXPOSURE_MS=500".to_owned()], + false, + ) + .expect("encodes SetExposure"); + + assert_eq!(bytes, vec![0xCA, 0xFE, 0x07, 0x01, 0xF4]); + + let decoder = Decoder::with_root(&db, "BaseCmdContainer").expect("cmd decoder"); + let packet = decoder.decode(&bytes).expect("decodes command"); + let values: Vec<(&str, RawValue<'_>)> = packet + .iter_named() + .map(|(name, val)| (name, val.raw.clone())) + .collect(); + assert_eq!( + values, + vec![ + ("OPCODE", RawValue::Unsigned(7)), + ("EXPOSURE_MS", RawValue::Unsigned(500)), + ] + ); + } +} diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index 8d643ee..299819d 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -20,6 +20,7 @@ use clap::{Parser, Subcommand}; use xtce_model::XtceDb; mod decode; +mod encode; mod info; mod pcap; mod pus; @@ -134,6 +135,35 @@ enum Command { limit: Option, }, + /// Assemble a binary CCSDS telemetry or telecommand packet from an XTCE definition. + Encode { + /// XTCE definition. Use '-' to read from standard input. + definition: PathBuf, + + /// Concrete container or MetaCommand name to encode. + target: String, + + /// Explicit root container to start inheritance walk from. + #[arg(long)] + root: Option, + + /// Field or argument assignment in NAME=VALUE form (repeatable). + #[arg(long = "set", short = 's')] + assignments: Vec, + + /// Write encoded packet here instead of standard output. + #[arg(long, short)] + out: Option, + + /// Emit lowercase hexadecimal text instead of raw binary bytes. + #[arg(long)] + hex: bool, + + /// Stamp the final 16 bits of the packet with an ECSS CRC-16-CCITT syndrome. + #[arg(long)] + crc: bool, + }, + /// Inspect ECSS-E-ST-70-41C (PUS-C) packet streams, run a HIL OBC session, or emit XTCE XML. Pus { /// File of concatenated CCSDS/PUS packets. Use '-' to read from standard input. @@ -143,6 +173,10 @@ enum Command { #[arg(long)] hil_demo: bool, + /// Bind a live UDP socket (e.g. 127.0.0.1:5006) serving the no_std HIL OBC responder. + #[arg(long)] + hil_udp: Option, + /// Emit a complete XTCE 1.2 XML mission definition for the ECSS PUS-C spacecraft profile. #[arg(long)] emit_xtce: bool, @@ -246,9 +280,27 @@ fn run(cli: Cli) -> Result<(), Box> { skip_header_bytes, limit, }), + Command::Encode { + definition, + target, + root, + assignments, + out, + hex, + crc, + } => run_encode( + &definition, + &target, + root.as_deref(), + &assignments, + out.as_deref(), + hex, + crc, + ), Command::Pus { packets, hil_demo, + hil_udp, emit_xtce, out, skip_header_bytes, @@ -256,6 +308,7 @@ fn run(cli: Cli) -> Result<(), Box> { } => pus::run(&pus::Options { packets: packets.as_deref(), hil_demo, + hil_udp: hil_udp.as_deref(), emit_xtce, out: out.as_deref(), skip_header_bytes, @@ -265,6 +318,29 @@ fn run(cli: Cli) -> Result<(), Box> { } } +fn run_encode( + definition: &Path, + target: &str, + root: Option<&str>, + assignments: &[String], + out: Option<&Path>, + hex: bool, + crc: bool, +) -> Result<(), Box> { + let db = load_db(definition)?; + encode::run_with_db( + &db, + &encode::Options { + target, + root, + assignments, + out, + hex, + crc, + }, + ) +} + fn run_wireshark( definition: &Path, root: Option<&str>, diff --git a/crates/xtce-cli/src/pus.rs b/crates/xtce-cli/src/pus.rs index e4b83fd..3bda026 100644 --- a/crates/xtce-cli/src/pus.rs +++ b/crates/xtce-cli/src/pus.rs @@ -7,14 +7,16 @@ use std::path::Path; use xtce_decode::PacketReader; use xtce_pus::{ AckFlags, FUNC_EO_OPTICAL_CAPTURE, HousekeepingMessage, MAX_HIL_FRAME_LEN, MemoryMessage, - MonitoringMessage, ObcHousekeeping, PusError, PusHeader, PusPacket, PusResponder, PusService, - ScheduleMessage, TcParams, TestMessage, VerificationReport, encode_tc, + MonitoringMessage, ObcHousekeeping, ParameterManagementMessage, PusError, PusHeader, PusPacket, + PusResponder, PusService, ScheduleMessage, TcParams, TestMessage, VerificationReport, + encode_tc, }; /// Configuration for `xtce pus`. pub struct Options<'a> { pub packets: Option<&'a Path>, pub hil_demo: bool, + pub hil_udp: Option<&'a str>, pub emit_xtce: bool, pub out: Option<&'a Path>, pub skip_header_bytes: usize, @@ -34,8 +36,8 @@ fn open_packet_source(packets: &Path) -> std::io::Result> { /// /// # Errors /// -/// Returns an error if no action (``, `--hil-demo`, or `--emit-xtce`) is specified or -/// if I/O fails. +/// Returns an error if no action (``, `--hil-demo`, `--hil-udp`, or `--emit-xtce`) is +/// specified or if I/O fails. pub fn run(options: &Options<'_>) -> Result<(), Box> { if options.emit_xtce { return write_pus_xtce(options.out); @@ -44,6 +46,13 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { let stdout = std::io::stdout(); let mut out = std::io::BufWriter::new(stdout.lock()); + if let Some(bind_addr) = options.hil_udp { + let socket = std::net::UdpSocket::bind(bind_addr)?; + serve_hil_udp(&socket, &mut out, options.limit)?; + out.flush()?; + return Ok(()); + } + if options.hil_demo { run_hil_demo(&mut out, options.out)?; out.flush()?; @@ -52,7 +61,7 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { let Some(packets_path) = options.packets else { return Err( - "provide a packet stream file (or '-'), pass --hil-demo, or pass --emit-xtce".into(), + "provide a packet stream file (or '-'), --hil-demo, --hil-udp, or --emit-xtce".into(), ); }; @@ -172,6 +181,7 @@ fn write_pus_packet( ), Ok(PusService::Schedule(sched)) => write_schedule_summary(out, &sched), Ok(PusService::Monitoring(mon)) => write_monitoring_summary(out, mon), + Ok(PusService::ParameterManagement(pm)) => write_param_mgmt_summary(out, pm), Ok(PusService::Test(TestMessage::AreYouAliveCommand)) => { writeln!(out, "AreYouAliveCommand") } @@ -336,6 +346,29 @@ fn write_monitoring_summary(out: &mut impl Write, mon: MonitoringMessage) -> std } } +fn write_param_mgmt_summary( + out: &mut impl Write, + pm: ParameterManagementMessage, +) -> std::io::Result<()> { + match pm { + ParameterManagementMessage::ReportRequest { param_id } => { + writeln!(out, "ParameterReportRequest(param=0x{param_id:04X})") + } + ParameterManagementMessage::ValueReport { param_id, value } => { + writeln!( + out, + "ParameterValueReport(param=0x{param_id:04X}, val={value})" + ) + } + ParameterManagementMessage::SetValue { param_id, value } => { + writeln!( + out, + "ParameterSetValue(param=0x{param_id:04X}, val={value})" + ) + } + } +} + fn run_hil_demo( out: &mut impl Write, capture_out: Option<&Path>, @@ -427,6 +460,50 @@ fn run_hil_demo( Ok(()) } +/// Runs a live UDP FlatSat OBC responder loop on `socket`, processing up to `limit` telecommands. +/// +/// # Errors +/// +/// Returns an error if socket I/O or stream writing fails. +pub fn serve_hil_udp( + socket: &std::net::UdpSocket, + out: &mut impl Write, + limit: Option, +) -> Result<(), Box> { + let mut responder = PusResponder::new(0x010, 0x0001); + let mut rx_buf = [0u8; 256]; + let mut tm_frames = [[0u8; MAX_HIL_FRAME_LEN]; 4]; + let mut tm_lens = [0usize; 4]; + let mut processed = 0usize; + let mut frame_index = 0usize; + + while limit.is_none_or(|max| processed < max) { + let (n, peer) = socket.recv_from(&mut rx_buf)?; + responder.tick_second(); + let tc_slice = &rx_buf[..n]; + + if let Ok(parsed_tc) = PusPacket::parse(tc_slice) { + write_pus_packet(out, frame_index, &parsed_tc)?; + } + frame_index += 1; + + if let Ok(tm_count) = responder.process_telecommand(tc_slice, &mut tm_frames, &mut tm_lens) + { + for slot in 0..tm_count { + let slice = &tm_frames[slot][..tm_lens[slot]]; + socket.send_to(slice, peer)?; + if let Ok(parsed_tm) = PusPacket::parse(slice) { + write_pus_packet(out, frame_index, &parsed_tm)?; + } + frame_index += 1; + } + } + processed += 1; + } + + Ok(()) +} + /// Complete XTCE 1.2 XML mission definition describing the ECSS-E-ST-70-41C (PUS-C) /// telemetry containers emitted by [`PusResponder`]. pub const ECSS_PUS_XTCE_XML: &str = r#" @@ -753,4 +830,64 @@ mod tests { assert!(packet.len() >= 15); } } + + #[test] + fn hil_udp_roundtrip_over_localhost_socket() { + let server_sock = std::net::UdpSocket::bind("127.0.0.1:0").expect("binds server"); + let server_addr = server_sock.local_addr().expect("server addr"); + + let client_sock = std::net::UdpSocket::bind("127.0.0.1:0").expect("binds client"); + client_sock + .set_read_timeout(Some(std::time::Duration::from_secs(2))) + .expect("timeout"); + + // Send one TC[17,1] Are-You-Alive telecommand datagram to the server socket + let mut tc_buf = [0u8; 32]; + let tc_len = xtce_pus::encode_tc( + &xtce_pus::TcParams { + apid: 0x010, + sequence_count: 1, + ack: xtce_pus::AckFlags::ACCEPT_AND_COMPLETE, + service: 17, + subtype: 1, + source_id: 0x0042, + }, + &[], + &mut tc_buf, + ) + .expect("TC[17,1]"); + client_sock + .send_to(&tc_buf[..tc_len], server_addr) + .expect("sends TC over UDP"); + + let mut log = Vec::new(); + super::serve_hil_udp(&server_sock, &mut log, Some(1)).expect("serves 1 UDP command"); + + // Receive all 3 response datagrams (TM[1,1], TM[17,2], TM[1,7]) + let mut rx = [0u8; 64]; + let (n0, _) = client_sock.recv_from(&mut rx).expect("TM[1,1]"); + assert_eq!( + xtce_pus::PusPacket::parse(&rx[..n0]) + .unwrap() + .header + .subtype(), + 1 + ); + let (n1, _) = client_sock.recv_from(&mut rx).expect("TM[17,2]"); + assert_eq!( + xtce_pus::PusPacket::parse(&rx[..n1]) + .unwrap() + .header + .service(), + 17 + ); + let (n2, _) = client_sock.recv_from(&mut rx).expect("TM[1,7]"); + assert_eq!( + xtce_pus::PusPacket::parse(&rx[..n2]) + .unwrap() + .header + .subtype(), + 7 + ); + } } diff --git a/crates/xtce-pus/README.md b/crates/xtce-pus/README.md index 5de5d2f..1f66d65 100644 --- a/crates/xtce-pus/README.md +++ b/crates/xtce-pus/README.md @@ -20,6 +20,7 @@ Space Packets, with a bare-metal Hardware-in-the-Loop (HIL) spacecraft responder - **ST\[11\] Time-Based Scheduling**: `TC[11,1..3]` Enable/Disable/Reset Schedule, `TC[11,4]` Insert Time-Tagged Activity, `TM[11,13]` Schedule Summary Report. - **ST\[12\] On-Board Monitoring (FDIR)**: `TC[12,1..2]` Enable/Disable Parameter Monitoring, `TM[12,12]` Check Transition Report. - **ST\[17\] Test Service**: `TC[17,1]` Are-You-Alive Connection Test and `TM[17,2]` Are-You-Alive Connection Report. + - **ST\[20\] On-Board Parameter Management**: `TC[20,1]` Report Parameter Value, `TM[20,2]` Parameter Value Report, `TC[20,3]` Set Parameter Value in flight. - **Dual-Use Telecommand Security (`TcSecurityGate`)**: constant-time 64-bit **SipHash-2-4 MAC** verification and monotonic 32-bit **Anti-Replay** counter protection for critical uplink commands. - **`PusResponder` HIL State Machine**: deterministic, zero-heap flight responder suitable for `thumbv7em-none-eabihf` (STM32 Cortex-M), RISC-V (ESP32), RP2040/RP2350, or desktop HIL benches. diff --git a/crates/xtce-pus/src/hil.rs b/crates/xtce-pus/src/hil.rs index 4f892a1..5e7f6c7 100644 --- a/crates/xtce-pus/src/hil.rs +++ b/crates/xtce-pus/src/hil.rs @@ -45,6 +45,9 @@ pub const FUNC_DPU_AI_INFERENCE: u16 = 0x0020; /// `ST[08]` Function ID: command spacecraft into `SAFE` mode (`mode = 0`). pub const FUNC_ENTER_SAFE_MODE: u16 = 0x00FF; +/// `ST[20]` On-Board Parameter ID: optical payload integration exposure time in microseconds. +pub const PARAM_EO_EXPOSURE_US: u16 = 0x0001; + /// Deterministic, zero-heap ECSS PUS spacecraft responder state machine. #[derive(Clone, Debug)] #[allow(clippy::struct_excessive_bools)] @@ -67,6 +70,8 @@ pub struct PusResponder { pub scheduled_count: u16, /// Whether `ST[12]` autonomous on-board parameter limit monitoring (FDIR) is enabled. pub monitoring_enabled: bool, + /// Tunable optical payload exposure duration in microseconds (`ST[20]`, `Param_ID = 1`). + pub eo_exposure_us: i32, /// On-board scratchpad RAM (`Memory_ID = 1`) accessible via `ST[06]` load/dump/check. pub scratchpad: [u8; OBC_SCRATCHPAD_LEN], } @@ -90,6 +95,7 @@ impl PusResponder { schedule_enabled: false, scheduled_count: 0, monitoring_enabled: false, + eo_exposure_us: 15_000, scratchpad: [0u8; OBC_SCRATCHPAD_LEN], } } @@ -231,6 +237,7 @@ impl PusResponder { self.emit_frame(17, 2, &[], out_frames, out_lens, count, max_slots)?; Ok(true) } + 20 => self.execute_st20(subtype, app_data, out_frames, out_lens, count, max_slots), _ => Ok(false), } } @@ -441,6 +448,47 @@ impl PusResponder { } } + #[allow(clippy::too_many_arguments)] + fn execute_st20( + &mut self, + subtype: u8, + app_data: &[u8], + out_frames: &mut [[u8; MAX_HIL_FRAME_LEN]], + out_lens: &mut [usize], + count: &mut usize, + max_slots: usize, + ) -> Result { + match subtype { + 1 if app_data.len() >= 2 => { + let param_id = u16::from_be_bytes([app_data[0], app_data[1]]); + if param_id != PARAM_EO_EXPOSURE_US { + return Ok(false); + } + let val_bytes = self.eo_exposure_us.to_be_bytes(); + let report = [ + app_data[0], + app_data[1], + val_bytes[0], + val_bytes[1], + val_bytes[2], + val_bytes[3], + ]; + self.emit_frame(20, 2, &report, out_frames, out_lens, count, max_slots)?; + Ok(true) + } + 3 if app_data.len() >= 6 => { + let param_id = u16::from_be_bytes([app_data[0], app_data[1]]); + if param_id != PARAM_EO_EXPOSURE_US { + return Ok(false); + } + self.eo_exposure_us = + i32::from_be_bytes([app_data[2], app_data[3], app_data[4], app_data[5]]); + Ok(true) + } + _ => Ok(false), + } + } + fn push_tm_1_1( &mut self, request_id: u32, diff --git a/crates/xtce-pus/src/lib.rs b/crates/xtce-pus/src/lib.rs index fc452c8..c445a87 100644 --- a/crates/xtce-pus/src/lib.rs +++ b/crates/xtce-pus/src/lib.rs @@ -37,7 +37,7 @@ pub use hil::{ ERR_CODE_CRC_MISMATCH, ERR_CODE_NOT_A_TC, ERR_CODE_UNSUPPORTED, EVENT_ID_CORRUPTED_TC, EVENT_ID_DPU_INFERENCE, EVENT_ID_EO_CAPTURE, EVENT_ID_HK_ENABLED, FUNC_DPU_AI_INFERENCE, FUNC_ENTER_SAFE_MODE, FUNC_EO_OPTICAL_CAPTURE, MAX_HIL_FRAME_LEN, OBC_SCRATCHPAD_LEN, - PusResponder, + PARAM_EO_EXPOSURE_US, PusResponder, }; pub use packet::{ AckFlags, CucTimestamp, PEC_LEN, PRIMARY_HEADER_LEN, PUS_VERSION_C, PusError, PusHeader, @@ -50,8 +50,8 @@ pub use security::{ }; pub use services::{ EventReport, EventSeverity, FunctionCall, HousekeepingMessage, MemoryMessage, - MonitoringMessage, ObcHousekeeping, PusService, ScheduleMessage, TestMessage, - VerificationReport, + MonitoringMessage, ObcHousekeeping, ParameterManagementMessage, PusService, ScheduleMessage, + TestMessage, VerificationReport, }; #[cfg(test)] diff --git a/crates/xtce-pus/src/services.rs b/crates/xtce-pus/src/services.rs index 45060f0..1e71b72 100644 --- a/crates/xtce-pus/src/services.rs +++ b/crates/xtce-pus/src/services.rs @@ -249,6 +249,30 @@ pub enum TestMessage { AreYouAliveReport, } +/// ECSS Service 20 (`ST[20]`) On-Board Parameter Management message. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum ParameterManagementMessage { + /// `TC[20,1]` — Request the current value of on-board parameter `param_id`. + ReportRequest { + /// 16-bit On-Board Parameter Identifier (`Param_ID`). + param_id: u16, + }, + /// `TM[20,2]` — Telemetry report carrying the current value of `param_id`. + ValueReport { + /// 16-bit On-Board Parameter Identifier (`Param_ID`). + param_id: u16, + /// Current 32-bit parameter value. + value: i32, + }, + /// `TC[20,3]` — Set the value of on-board parameter `param_id` in flight. + SetValue { + /// 16-bit On-Board Parameter Identifier (`Param_ID`). + param_id: u16, + /// New 32-bit parameter value. + value: i32, + }, +} + /// High-level decoded ECSS PUS service payload. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum PusService<'a> { @@ -268,6 +292,8 @@ pub enum PusService<'a> { Monitoring(MonitoringMessage), /// `ST[17]` Test service message. Test(TestMessage), + /// `ST[20]` On-Board Parameter Management message. + ParameterManagement(ParameterManagementMessage), /// Any other service/subtype pair with its raw application data slice. Custom { /// ECSS service type (`ST[x]`). @@ -308,6 +334,7 @@ impl<'a> PusPacket<'a> { app_data: data, }), }, + 20 => Self::decode_st20(self.header.is_telecommand(), subtype, data), _ => Ok(PusService::Custom { service, subtype, @@ -598,4 +625,42 @@ impl<'a> PusPacket<'a> { }), } } + + fn decode_st20(is_tc: bool, subtype: u8, data: &'a [u8]) -> Result, PusError> { + match (is_tc, subtype) { + (true, 1) => { + if data.len() < 2 { + return Err(PusError::MalformedServiceData { + service: 20, + subtype, + }); + } + let param_id = u16::from_be_bytes([data[0], data[1]]); + Ok(PusService::ParameterManagement( + ParameterManagementMessage::ReportRequest { param_id }, + )) + } + (false, 2) | (true, 3) => { + if data.len() < 6 { + return Err(PusError::MalformedServiceData { + service: 20, + subtype, + }); + } + let param_id = u16::from_be_bytes([data[0], data[1]]); + let value = i32::from_be_bytes([data[2], data[3], data[4], data[5]]); + let msg = if is_tc { + ParameterManagementMessage::SetValue { param_id, value } + } else { + ParameterManagementMessage::ValueReport { param_id, value } + }; + Ok(PusService::ParameterManagement(msg)) + } + _ => Ok(PusService::Custom { + service: 20, + subtype, + app_data: data, + }), + } + } } From 89ec9cb0acb76f7360d73109147a9aab42caab04 Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Thu, 19 Nov 2026 13:44:40 +0100 Subject: [PATCH 11/13] feat(cli,docs): add xtce diff, validate, sim commands and 2027 architecture ADR baseline (v0.2.1) --- Cargo.lock | 14 +- Cargo.toml | 10 +- crates/xtce-cli/README.md | 11 + crates/xtce-cli/src/diff.rs | 583 ++++++++++++++++++++++++++++++++ crates/xtce-cli/src/main.rs | 115 +++++++ crates/xtce-cli/src/sim.rs | 264 +++++++++++++++ crates/xtce-cli/src/validate.rs | 299 ++++++++++++++++ docs/AUDIT_AND_ADR_2027.md | 325 ++++++++++++++++++ 8 files changed, 1609 insertions(+), 12 deletions(-) create mode 100644 crates/xtce-cli/src/diff.rs create mode 100644 crates/xtce-cli/src/sim.rs create mode 100644 crates/xtce-cli/src/validate.rs create mode 100644 docs/AUDIT_AND_ADR_2027.md diff --git a/Cargo.lock b/Cargo.lock index 72b468d..2ff633f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -915,7 +915,7 @@ checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" [[package]] name = "xtask" -version = "0.2.0" +version = "0.2.1" dependencies = [ "clap", "serde_json", @@ -925,7 +925,7 @@ dependencies = [ [[package]] name = "xtce-cli" -version = "0.2.0" +version = "0.2.1" dependencies = [ "clap", "xtce-codegen", @@ -936,7 +936,7 @@ dependencies = [ [[package]] name = "xtce-codegen" -version = "0.2.0" +version = "0.2.1" dependencies = [ "criterion", "prettyplease", @@ -950,7 +950,7 @@ dependencies = [ [[package]] name = "xtce-codegen-e2e" -version = "0.2.0" +version = "0.2.1" dependencies = [ "xtce-codegen", "xtce-decode", @@ -959,7 +959,7 @@ dependencies = [ [[package]] name = "xtce-decode" -version = "0.2.0" +version = "0.2.1" dependencies = [ "criterion", "proptest", @@ -969,7 +969,7 @@ dependencies = [ [[package]] name = "xtce-model" -version = "0.2.0" +version = "0.2.1" dependencies = [ "criterion", "proptest", @@ -979,7 +979,7 @@ dependencies = [ [[package]] name = "xtce-pus" -version = "0.2.0" +version = "0.2.1" [[package]] name = "zerocopy" diff --git a/Cargo.toml b/Cargo.toml index 6e9a93f..306cebe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ members = ["crates/*", "xtask"] exclude = ["crates/xtce-py"] [workspace.package] -version = "0.2.0" +version = "0.2.1" edition = "2024" rust-version = "1.85" license = "MIT OR Apache-2.0" @@ -15,10 +15,10 @@ repository = "https://github.com/RustSpaceLab/xtce-rs" authors = ["Maciej Myszkiewicz"] [workspace.dependencies] -xtce-model = { path = "crates/xtce-model", version = "0.2.0" } -xtce-decode = { path = "crates/xtce-decode", version = "0.2.0" } -xtce-codegen = { path = "crates/xtce-codegen", version = "0.2.0" } -xtce-pus = { path = "crates/xtce-pus", version = "0.2.0" } +xtce-model = { path = "crates/xtce-model", version = "0.2.1" } +xtce-decode = { path = "crates/xtce-decode", version = "0.2.1" } +xtce-codegen = { path = "crates/xtce-codegen", version = "0.2.1" } +xtce-pus = { path = "crates/xtce-pus", version = "0.2.1" } # Keep this list short and justified — see CONTRIBUTING.md rule 7. anyhow = "1" diff --git a/crates/xtce-cli/README.md b/crates/xtce-cli/README.md index 1266ee6..ce90fe2 100644 --- a/crates/xtce-cli/README.md +++ b/crates/xtce-cli/README.md @@ -41,6 +41,17 @@ $ xtce pus --hil-demo -o hil_session.bin $ xtce pus --hil-udp 127.0.0.1:5006 $ xtce pus --emit-xtce -o ecss_pus.xml $ xtce decode ecss_pus.xml hil_session.bin --format table + +# 7. Validate an XTCE definition or export a normalized JSON metadata dictionary +$ xtce validate ecss_pus.xml --strict +$ xtce validate ecss_pus.xml --json > metadata.json + +# 8. Compare two XTCE definitions and classify changes (BREAKING, WARNING, COMPATIBLE) +$ xtce diff mission_v1.xml mission_v2.xml --fail-on-breaking + +# 9. Simulate a deterministic CCSDS / ECSS PUS-C telemetry stream (with fault injection) +$ xtce sim --scenario voltage-drop --packets 20 --seed 42 -o fault_pass.bin +$ xtce sim --scenario overheat --packets 20 --seed 42 --pcap -o overheat_pass.pcap ``` Part of [RustSpaceLab/xtce-rs](https://github.com/RustSpaceLab/xtce-rs). diff --git a/crates/xtce-cli/src/diff.rs b/crates/xtce-cli/src/diff.rs new file mode 100644 index 0000000..58ac622 --- /dev/null +++ b/crates/xtce-cli/src/diff.rs @@ -0,0 +1,583 @@ +//! `xtce diff` — semantic comparison of two XTCE definitions at the canonical IR and layout level. +//! +//! Compares two mission definitions (`old` and `new`) and classifies every difference as: +//! - `BREAKING`: wire-format or decoding incompatibility (removed parameter/container, changed +//! type family, bit width, signedness, byte order, removed/relabeled enumeration entry, or +//! shifted bit offset inside a container). +//! - `WARNING`: backward-compatible extension that downstream consumers should review (added +//! enumeration label, appended trailing field extending a container). +//! - `COMPATIBLE`: additive definition change that does not alter existing packet layouts +//! (new standalone parameter or new container). + +use std::collections::BTreeMap; +use std::io::Write; + +use xtce_codegen::{ContainerPlan, Plan}; +use xtce_model::{ByteOrder, DataEncoding, Parameter, ParameterType, TypeKind, XtceDb}; + +/// Classification of a semantic difference between two XTCE definitions. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub enum Severity { + /// Wire-format or decoding incompatibility. + Breaking, + /// Non-breaking change that may affect consumers (e.g. new enum variant or trailing field). + Warning, + /// Purely additive change. + Compatible, +} + +impl Severity { + /// Short uppercase tag used in reports (`BREAKING`, `WARNING`, `COMPATIBLE`). + #[must_use] + pub const fn label(self) -> &'static str { + match self { + Self::Breaking => "BREAKING", + Self::Warning => "WARNING", + Self::Compatible => "COMPATIBLE", + } + } +} + +/// One semantic change detected between two XTCE definitions. +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct Finding { + pub severity: Severity, + pub subject: String, + pub detail: String, +} + +/// Complete semantic diff report between two [`XtceDb`] definitions. +#[derive(Clone, Debug, Default)] +pub struct DiffReport { + pub findings: Vec, + pub unchanged_parameters: usize, + pub unchanged_containers: usize, +} + +impl DiffReport { + /// Number of `BREAKING` findings in the report. + #[must_use] + pub fn breaking_count(&self) -> usize { + self.findings + .iter() + .filter(|f| f.severity == Severity::Breaking) + .count() + } + + /// Number of `WARNING` findings in the report. + #[must_use] + pub fn warning_count(&self) -> usize { + self.findings + .iter() + .filter(|f| f.severity == Severity::Warning) + .count() + } +} + +/// Compares `old_db` and `new_db` at the canonical IR and flattened container layout levels. +#[must_use] +pub fn compare(old_db: &XtceDb, new_db: &XtceDb, root: Option<&str>) -> DiffReport { + let mut report = DiffReport::default(); + + compare_parameters(old_db, new_db, &mut report); + compare_containers(old_db, new_db, root, &mut report); + + report +} + +fn compare_parameters(old_db: &XtceDb, new_db: &XtceDb, report: &mut DiffReport) { + let mut old_params: BTreeMap<&str, &Parameter> = BTreeMap::new(); + for p in old_db.parameters() { + old_params.insert(old_db.name(p.name), p); + } + + let mut new_params: BTreeMap<&str, &Parameter> = BTreeMap::new(); + for p in new_db.parameters() { + new_params.insert(new_db.name(p.name), p); + } + + for (&name, &old_p) in &old_params { + if let Some(&new_p) = new_params.get(name) { + let before = report.findings.len(); + diff_parameter_pair(name, old_db, old_p, new_db, new_p, &mut report.findings); + if report.findings.len() == before { + report.unchanged_parameters += 1; + } + } else { + push_finding( + &mut report.findings, + Severity::Breaking, + name, + "parameter removed from definition", + ); + } + } + + for &name in new_params.keys() { + if !old_params.contains_key(name) { + push_finding( + &mut report.findings, + Severity::Compatible, + name, + "parameter added to definition", + ); + } + } +} + +fn diff_parameter_pair( + name: &str, + old_db: &XtceDb, + old_p: &Parameter, + new_db: &XtceDb, + new_p: &Parameter, + findings: &mut Vec, +) { + let (Some(old_ty), Some(new_ty)) = ( + old_db.parameter_type(old_p.type_id), + new_db.parameter_type(new_p.type_id), + ) else { + return; + }; + + let old_sig = type_signature(old_ty); + let new_sig = type_signature(new_ty); + if old_sig != new_sig { + findings.push(Finding { + severity: Severity::Breaking, + subject: name.to_owned(), + detail: format!("type changed: {old_sig} -> {new_sig}"), + }); + return; + } + + if let (TypeKind::Enumerated(old_enums), TypeKind::Enumerated(new_enums)) = + (&old_ty.kind, &new_ty.kind) + { + diff_enumerations(name, old_db, old_enums, new_db, new_enums, findings); + } +} + +fn diff_enumerations( + param_name: &str, + old_db: &XtceDb, + old_enums: &xtce_model::EnumerationList, + new_db: &XtceDb, + new_enums: &xtce_model::EnumerationList, + findings: &mut Vec, +) { + let mut old_by_label: BTreeMap<&str, (i128, i128)> = BTreeMap::new(); + for item in old_enums.entries() { + let label = old_db.name(item.label); + old_by_label.insert(label, (item.value, item.max_value)); + } + + let mut new_by_label: BTreeMap<&str, (i128, i128)> = BTreeMap::new(); + for item in new_enums.entries() { + let label = new_db.name(item.label); + new_by_label.insert(label, (item.value, item.max_value)); + } + + for (&label, &(old_val, old_max)) in &old_by_label { + match new_by_label.get(label) { + None => push_enum_removed(findings, param_name, label), + Some(&(new_val, new_max)) if (old_val, old_max) != (new_val, new_max) => { + push_enum_revalued(findings, param_name, label, old_val, new_val); + } + Some(_) => {} + } + } + + for &label in new_by_label.keys() { + if !old_by_label.contains_key(label) { + push_enum_added(findings, param_name, label); + } + } +} + +fn push_finding(findings: &mut Vec, severity: Severity, subject: &str, detail: &str) { + findings.push(Finding { + severity, + subject: subject.to_owned(), + detail: detail.to_owned(), + }); +} + +fn push_enum_removed(findings: &mut Vec, param_name: &str, label: &str) { + findings.push(Finding { + severity: Severity::Breaking, + subject: param_name.to_owned(), + detail: format!("enum value removed: {label}"), + }); +} + +fn push_enum_revalued( + findings: &mut Vec, + param_name: &str, + label: &str, + old_val: i128, + new_val: i128, +) { + findings.push(Finding { + severity: Severity::Breaking, + subject: param_name.to_owned(), + detail: format!("enum {label} value changed: {old_val} -> {new_val}"), + }); +} + +fn push_enum_added(findings: &mut Vec, param_name: &str, label: &str) { + findings.push(Finding { + severity: Severity::Warning, + subject: param_name.to_owned(), + detail: format!("enum value added: {label}"), + }); +} + +fn type_signature(ty: &ParameterType) -> String { + let family = ty.kind.label(); + let bits = ty + .fixed_size_in_bits() + .map_or_else(|| "var".to_owned(), |b| b.to_string()); + let byte_order = match &ty.encoding { + DataEncoding::Integer(enc) => enc.byte_order, + DataEncoding::Float(enc) => enc.byte_order, + DataEncoding::String(enc) => enc.byte_order, + DataEncoding::Binary(_) | DataEncoding::None => ByteOrder::MostSignificantFirst, + }; + let order = match byte_order { + ByteOrder::MostSignificantFirst => "be", + ByteOrder::LeastSignificantFirst => "le", + }; + let coding = match &ty.encoding { + DataEncoding::Integer(int_enc) => match int_enc.coding { + xtce_model::IntegerCoding::Unsigned => "uint", + xtce_model::IntegerCoding::TwosComplement => "int-2c", + xtce_model::IntegerCoding::OnesComplement => "int-1c", + xtce_model::IntegerCoding::SignMagnitude => "int-sm", + }, + DataEncoding::Float(_) => "float", + DataEncoding::String(_) => "str", + DataEncoding::Binary(_) => "bin", + DataEncoding::None => family, + }; + format!("{coding}{bits}({family},{order})") +} + +fn compare_containers( + old_db: &XtceDb, + new_db: &XtceDb, + root: Option<&str>, + report: &mut DiffReport, +) { + let opts = xtce_codegen::Options { + root: root.map(str::to_owned), + source_label: None, + }; + let (Ok(old_plan), Ok(new_plan)) = ( + xtce_codegen::plan(old_db, &opts), + xtce_codegen::plan(new_db, &opts), + ) else { + return; + }; + + diff_plans(&old_plan, &new_plan, report); +} + +fn diff_plans(old_plan: &Plan, new_plan: &Plan, report: &mut DiffReport) { + let mut old_containers: BTreeMap<&str, &ContainerPlan> = BTreeMap::new(); + for c in &old_plan.containers { + old_containers.insert(c.xtce_name.as_str(), c); + } + + let mut new_containers: BTreeMap<&str, &ContainerPlan> = BTreeMap::new(); + for c in &new_plan.containers { + new_containers.insert(c.xtce_name.as_str(), c); + } + + for (&name, &old_c) in &old_containers { + if let Some(&new_c) = new_containers.get(name) { + let before = report.findings.len(); + diff_container_pair(name, old_c, new_c, &mut report.findings); + if report.findings.len() == before { + report.unchanged_containers += 1; + } + } else { + push_finding( + &mut report.findings, + Severity::Breaking, + name, + "container removed from definition", + ); + } + } + + for &name in new_containers.keys() { + if !old_containers.contains_key(name) { + push_finding( + &mut report.findings, + Severity::Compatible, + name, + "container added to definition", + ); + } + } +} + +fn diff_container_pair( + container_name: &str, + old_c: &ContainerPlan, + new_c: &ContainerPlan, + findings: &mut Vec, +) { + let mut old_fields: BTreeMap<&str, (Option, Option)> = BTreeMap::new(); + for f in &old_c.fields { + old_fields.insert(f.xtce_name.as_str(), (f.bit_offset, f.width.fixed())); + } + + let mut new_fields: BTreeMap<&str, (Option, Option)> = BTreeMap::new(); + for f in &new_c.fields { + new_fields.insert(f.xtce_name.as_str(), (f.bit_offset, f.width.fixed())); + } + + for (&field_name, &(old_off, old_w)) in &old_fields { + match new_fields.get(field_name) { + None => push_field_removed(findings, container_name, field_name), + Some(&(new_off, new_w)) => { + if old_off != new_off { + push_offset_changed(findings, container_name, field_name, old_off, new_off); + } + if old_w != new_w { + push_width_changed(findings, container_name, field_name, old_w, new_w); + } + } + } + } + + for (&field_name, &(new_off, _)) in &new_fields { + if !old_fields.contains_key(field_name) { + push_field_added(findings, container_name, field_name, new_off); + } + } +} + +fn push_field_removed(findings: &mut Vec, container: &str, field: &str) { + findings.push(Finding { + severity: Severity::Breaking, + subject: container.to_owned(), + detail: format!("field {field} removed from container"), + }); +} + +fn push_offset_changed( + findings: &mut Vec, + container: &str, + field: &str, + old_off: Option, + new_off: Option, +) { + findings.push(Finding { + severity: Severity::Breaking, + subject: container.to_owned(), + detail: format!( + "field {field} bit offset changed: {} -> {}", + old_off.map_or_else(|| "dynamic".to_owned(), |v| v.to_string()), + new_off.map_or_else(|| "dynamic".to_owned(), |v| v.to_string()) + ), + }); +} + +fn push_width_changed( + findings: &mut Vec, + container: &str, + field: &str, + old_w: Option, + new_w: Option, +) { + findings.push(Finding { + severity: Severity::Breaking, + subject: container.to_owned(), + detail: format!( + "field {field} bit width changed: {} -> {}", + old_w.map_or_else(|| "dynamic".to_owned(), |v| v.to_string()), + new_w.map_or_else(|| "dynamic".to_owned(), |v| v.to_string()) + ), + }); +} + +fn push_field_added( + findings: &mut Vec, + container: &str, + field: &str, + new_off: Option, +) { + findings.push(Finding { + severity: Severity::Warning, + subject: container.to_owned(), + detail: format!( + "field {field} added to container at bit {}", + new_off.map_or_else(|| "dynamic".to_owned(), |v| v.to_string()) + ), + }); +} + +/// CLI options for `xtce diff`. +pub struct Options<'a> { + pub root: Option<&'a str>, + pub fail_on_breaking: bool, +} + +/// Runs `xtce diff` against `old_db` and `new_db` and prints the report to standard output. +/// +/// # Errors +/// +/// Returns an error if I/O fails or if `fail_on_breaking` is set and breaking changes exist. +pub fn run( + old_db: &XtceDb, + new_db: &XtceDb, + opts: &Options<'_>, +) -> Result<(), Box> { + let report = compare(old_db, new_db, opts.root); + let mut stdout = std::io::stdout().lock(); + write_text_report(&mut stdout, &report)?; + if opts.fail_on_breaking && report.breaking_count() > 0 { + return Err(format!( + "detected {} breaking change(s) between definitions", + report.breaking_count() + ) + .into()); + } + Ok(()) +} + +/// Writes a human-readable semantic diff report to `out`. +/// +/// # Errors +/// +/// Returns an I/O error if writing to `out` fails. +pub fn write_text_report(out: &mut impl Write, report: &DiffReport) -> std::io::Result<()> { + for finding in &report.findings { + writeln!(out, "{} {}", finding.severity.label(), finding.subject)?; + writeln!(out, " {}\n", finding.detail)?; + } + writeln!( + out, + "OK {} parameter(s) unchanged, {} container(s) unchanged ({} breaking, {} warning)", + report.unchanged_parameters, + report.unchanged_containers, + report.breaking_count(), + report.warning_count() + ) +} + +#[cfg(test)] +mod tests { + use xtce_model::XtceDb; + + use super::{Severity, compare, write_text_report}; + + const V1_XML: &str = r#" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +"#; + + const V2_XML: &str = r#" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +"#; + + #[test] + fn identical_definitions_report_zero_findings() { + let db1 = XtceDb::from_xml(V1_XML).expect("v1 loads"); + let db2 = XtceDb::from_xml(V1_XML).expect("v1 copy loads"); + let report = compare(&db1, &db2, None); + + assert_eq!(report.findings.len(), 0); + assert_eq!(report.unchanged_parameters, 3); + assert_eq!(report.unchanged_containers, 1); + } + + #[test] + fn detects_breaking_type_and_offset_shifts_and_warning_enum_addition() { + let db1 = XtceDb::from_xml(V1_XML).expect("v1 loads"); + let db2 = XtceDb::from_xml(V2_XML).expect("v2 loads"); + let report = compare(&db1, &db2, None); + + assert!(report.breaking_count() >= 2); + assert!(report.warning_count() >= 1); + + let mut buf = Vec::new(); + write_text_report(&mut buf, &report).expect("writes report"); + let text = String::from_utf8(buf).expect("utf8"); + + assert!(text.contains("BREAKING BATTERY_VOLTAGE")); + assert!(text.contains("type changed: uint16(integer,be) -> float32(float,be)")); + assert!(text.contains("WARNING SATELLITE_MODE")); + assert!(text.contains("enum value added: SAFE_MODE")); + assert!(text.contains("BREAKING CCSDSPacket")); + assert!(text.contains("field POWER_STATUS bit offset changed: 24 -> 40")); + assert!( + report + .findings + .iter() + .any(|f| f.severity == Severity::Breaking && f.subject == "BATTERY_VOLTAGE") + ); + } +} diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index 299819d..4407196 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -20,10 +20,13 @@ use clap::{Parser, Subcommand}; use xtce_model::XtceDb; mod decode; +mod diff; mod encode; mod info; mod pcap; mod pus; +mod sim; +mod validate; mod wireshark; #[derive(Parser)] @@ -203,6 +206,64 @@ enum Command { #[arg(long, default_value_t = 10)] iterations: u32, }, + + /// Compare two XTCE definitions and classify changes (BREAKING, WARNING, COMPATIBLE). + Diff { + /// Previous (baseline) XTCE definition file. + old: PathBuf, + + /// New (candidate) XTCE definition file. + new: PathBuf, + + /// Explicit root container to start inheritance and bit-offset analysis from. + #[arg(long)] + root: Option, + + /// Exit with a non-zero status code when BREAKING changes are detected. + #[arg(long)] + fail_on_breaking: bool, + }, + + /// Validate an XTCE definition for structural, semantic, and codegen readiness, or emit JSON metadata. + Validate { + /// XTCE definition. Use '-' to read from standard input. + definition: PathBuf, + + /// Explicit root container to start from. + #[arg(long)] + root: Option, + + /// Emit a canonical JSON metadata dictionary (parameters, containers, telecommands) instead of the text report. + #[arg(long)] + json: bool, + + /// Fail with a non-zero exit code on warnings as well as errors. + #[arg(long)] + strict: bool, + }, + + /// Generate a deterministic CCSDS / ECSS PUS-C mission telemetry stream (with optional fault injection). + Sim { + /// Mission scenario to simulate. + #[arg(long, value_enum, default_value_t = sim::Scenario::Nominal)] + scenario: sim::Scenario, + + /// Number of telemetry packets to generate. + #[arg(long, default_value_t = 20)] + packets: usize, + + /// Deterministic PRNG seed (SplitMix64) for reproducible sensor noise. + #[arg(long, default_value_t = 42)] + seed: u64, + + /// Wrap the generated packet stream in a libpcap (.pcap) DLT_USER0 container for Wireshark. + #[arg(long)] + pcap: bool, + + /// Write generated packets here instead of standard output. + #[arg(long, short)] + out: Option, + }, } fn main() -> ExitCode { @@ -234,6 +295,7 @@ fn load_db(path: &Path) -> Result> { } } +#[allow(clippy::too_many_lines)] fn run(cli: Cli) -> Result<(), Box> { match cli.command { Command::Info { files, verbose } => run_info(&files, verbose), @@ -315,9 +377,62 @@ fn run(cli: Cli) -> Result<(), Box> { limit, }), Command::Bench { file, iterations } => run_bench(&file, iterations), + Command::Diff { + old, + new, + root, + fail_on_breaking, + } => run_diff(&old, &new, root.as_deref(), fail_on_breaking), + Command::Validate { + definition, + root, + json, + strict, + } => run_validate(&definition, root.as_deref(), json, strict), + Command::Sim { + scenario, + packets, + seed, + pcap, + out, + } => sim::run(&sim::Options { + scenario, + packets, + seed, + pcap_format: pcap, + out: out.as_deref(), + }), } } +fn run_diff( + old: &Path, + new: &Path, + root: Option<&str>, + fail_on_breaking: bool, +) -> Result<(), Box> { + let old_db = load_db(old)?; + let new_db = load_db(new)?; + diff::run( + &old_db, + &new_db, + &diff::Options { + root, + fail_on_breaking, + }, + ) +} + +fn run_validate( + definition: &Path, + root: Option<&str>, + json: bool, + strict: bool, +) -> Result<(), Box> { + let db = load_db(definition)?; + validate::run(&db, &validate::Options { root, json, strict }) +} + fn run_encode( definition: &Path, target: &str, diff --git a/crates/xtce-cli/src/sim.rs b/crates/xtce-cli/src/sim.rs new file mode 100644 index 0000000..e514e20 --- /dev/null +++ b/crates/xtce-cli/src/sim.rs @@ -0,0 +1,264 @@ +//! `xtce sim` — deterministic mission telemetry simulator with fault-injection scenarios. +//! +//! Generates reproducible CCSDS / ECSS-E-ST-70-41C (PUS-C) telemetry streams driven by a +//! deterministic 64-bit SplitMix64 PRNG (`--seed`). Every packet produced is described by the +//! canonical `xtce pus --emit-xtce` mission definition, enabling end-to-end testing of +//! `xtce decode`, `xtce pus`, `xtce pcap`, and Wireshark dissectors under both nominal +//! orbital conditions and realistic spacecraft fault scenarios. + +use std::io::{Cursor, Write}; +use std::path::Path; + +use xtce_decode::PacketReader; +use xtce_pus::{CucTimestamp, MAX_HIL_FRAME_LEN, ObcHousekeeping, TmParams, encode_tm}; + +use crate::pcap; + +/// Fault-injection or nominal simulation profile. +#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)] +pub enum Scenario { + /// Nominal orbital pass: stable 28.2 V bus, 22.5 °C OBC, and periodic `TM[3,25]` / `TM[17,2]`. + Nominal, + /// Eclipse battery under-voltage: bus drops to 21.4 V, triggering `TM[5,2]` and `SAFE` mode. + VoltageDrop, + /// Thermal runaway: OBC rises to +68.5 °C, triggering `TM[5,2]` anomaly and `SAFE` mode. + Overheat, + /// RF downlink dropout: sequence counter jumps across a lost window, followed by link recovery. + CommLoss, + /// On-board watchdog reset mid-pass: uptime and sequence counters reset with a boot event. + Reboot, +} + +/// Configuration for `xtce sim`. +pub struct Options<'a> { + pub scenario: Scenario, + pub packets: usize, + pub seed: u64, + pub pcap_format: bool, + pub out: Option<&'a Path>, +} + +/// Deterministic SplitMix64 pseudo-random number generator. +struct SplitMix64 { + state: u64, +} + +impl SplitMix64 { + const fn new(seed: u64) -> Self { + Self { state: seed } + } + + const fn next_u64(&mut self) -> u64 { + self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] + const fn jitter_i16(&mut self, span: u16) -> i16 { + if span == 0 { + return 0; + } + let r = (self.next_u64() % ((span as u64) * 2 + 1)) as i16; + r - (span as i16) + } +} + +/// Generates a deterministic sequence of CCSDS / ECSS PUS-C packets for `scenario`. +#[must_use] +#[allow( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_sign_loss +)] +pub fn generate_stream(scenario: Scenario, packet_count: usize, seed: u64) -> Vec { + let mut rng = SplitMix64::new(seed); + let mut stream = Vec::with_capacity(packet_count * 36); + + let apid: u16 = 0x010; + let destination_id: u16 = 0x0001; + let mut seq_count: u16 = 0; + let mut msg_counter: u16 = 0; + let mut uptime_s: u32 = 100; + let mut mode: u8 = 2; // NOMINAL + let mut frame_buf = [0u8; MAX_HIL_FRAME_LEN]; + + let fault_step = (packet_count / 2).max(1); + + for step in 0..packet_count { + uptime_s = uptime_s.wrapping_add(1); + let v_jitter = rng.jitter_i16(25); + let t_jitter = rng.jitter_i16(10); + + let mut bus_voltage_mv: u16 = (28_200i32 + i32::from(v_jitter)) as u16; + let mut obc_temp_cdeg: i16 = 2_250 + t_jitter; + + match scenario { + Scenario::VoltageDrop if step >= fault_step => { + let drop = ((step - fault_step + 1) * 900).min(6_800) as u16; + bus_voltage_mv = bus_voltage_mv.saturating_sub(drop); + if bus_voltage_mv < 24_000 { + mode = 0; // SAFE + } + } + Scenario::Overheat if step >= fault_step => { + let rise = ((step - fault_step + 1) * 650).min(4_600) as i16; + obc_temp_cdeg = obc_temp_cdeg.saturating_add(rise); + if obc_temp_cdeg > 5_500 { + mode = 0; // SAFE + } + } + Scenario::CommLoss if step == fault_step => { + seq_count = (seq_count + 17) & 0x3FFF; + } + Scenario::Reboot if step == fault_step => { + uptime_s = 1; + seq_count = 0; + mode = 0; // Boot into SAFE mode + } + _ => {} + } + + let (service, subtype, payload_len, payload) = + if step == fault_step && scenario != Scenario::Nominal { + let (ev_id, aux_val): (u16, u16) = match scenario { + Scenario::VoltageDrop => (0x1201, bus_voltage_mv), + Scenario::Overheat => (0x1202, obc_temp_cdeg as u16), + Scenario::CommLoss => (0x0502, 17), + Scenario::Reboot => (0x0503, 1), + Scenario::Nominal => (0x0000, 0), + }; + let id_b = ev_id.to_be_bytes(); + let aux_b = aux_val.to_be_bytes(); + let mut app = [0u8; 11]; + app[0] = id_b[0]; + app[1] = id_b[1]; + app[2] = aux_b[0]; + app[3] = aux_b[1]; + (5u8, 2u8, 4usize, app) + } else if step % 5 == 4 { + (17u8, 2u8, 0usize, [0u8; 11]) + } else { + let hk = ObcHousekeeping { + uptime_s, + bus_voltage_mv, + obc_temp_cdeg, + mode, + }; + (3u8, 25u8, 11usize, hk.to_app_data()) + }; + + let params = TmParams { + apid, + sequence_count: seq_count, + service, + subtype, + msg_counter, + destination_id, + timestamp: CucTimestamp { + coarse_seconds: uptime_s, + fine_subseconds: 0, + }, + }; + + if let Ok(written) = encode_tm(¶ms, &payload[..payload_len], &mut frame_buf) { + stream.extend_from_slice(&frame_buf[..written]); + } + + seq_count = (seq_count + 1) & 0x3FFF; + msg_counter = msg_counter.wrapping_add(1); + } + + stream +} + +/// Executes `xtce sim`. +/// +/// # Errors +/// +/// Returns an error if writing to the output file or stdout fails. +pub fn run(options: &Options<'_>) -> Result<(), Box> { + let raw_stream = generate_stream(options.scenario, options.packets, options.seed); + + let output_bytes = if options.pcap_format { + let mut reader = PacketReader::new(Cursor::new(raw_stream), 0); + let mut pcap_buf = Vec::new(); + pcap::write_stream(&mut reader, &mut pcap_buf, None)?; + pcap_buf + } else { + raw_stream + }; + + match options.out { + Some(path) if path.as_os_str() != "-" => { + std::fs::write(path, &output_bytes)?; + eprintln!( + "simulated {} packet(s) (scenario={:?}, seed={}, {} bytes) to {}", + options.packets, + options.scenario, + options.seed, + output_bytes.len(), + path.display() + ); + } + _ => { + let stdout = std::io::stdout(); + let mut out = std::io::BufWriter::new(stdout.lock()); + out.write_all(&output_bytes)?; + out.flush()?; + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use xtce_decode::{Decoder, PacketIter}; + use xtce_model::XtceDb; + use xtce_pus::PusPacket; + + use super::{Scenario, generate_stream}; + use crate::pus::ECSS_PUS_XTCE_XML; + + #[test] + fn same_seed_produces_identical_byte_stream() { + let s1 = generate_stream(Scenario::VoltageDrop, 16, 42); + let s2 = generate_stream(Scenario::VoltageDrop, 16, 42); + let s3 = generate_stream(Scenario::VoltageDrop, 16, 99); + + assert_eq!(s1, s2); + assert_ne!(s1, s3); + } + + #[test] + fn every_scenario_decodes_end_to_end_through_xtce_and_pus() { + let db = XtceDb::from_xml(ECSS_PUS_XTCE_XML).expect("PUS XTCE loads"); + let decoder = Decoder::new(&db).expect("decoder"); + + for scenario in [ + Scenario::Nominal, + Scenario::VoltageDrop, + Scenario::Overheat, + Scenario::CommLoss, + Scenario::Reboot, + ] { + let stream = generate_stream(scenario, 12, 1337); + let mut count = 0usize; + for framed in PacketIter::new(&stream, 0) { + let framed = framed.expect("well-framed CCSDS packet"); + let pus = PusPacket::parse(framed.bytes()).expect("valid CRC-16-CCITT PUS frame"); + pus.decode_service().expect("valid ECSS PUS service"); + + let xtce_pkt = decoder + .decode(framed.bytes()) + .expect("decodes against ECSS_PUS_XTCE_XML"); + assert!(xtce_pkt.len() >= 15); + count += 1; + } + assert_eq!(count, 12); + } + } +} diff --git a/crates/xtce-cli/src/validate.rs b/crates/xtce-cli/src/validate.rs new file mode 100644 index 0000000..59d83fb --- /dev/null +++ b/crates/xtce-cli/src/validate.rs @@ -0,0 +1,299 @@ +//! `xtce validate` — semantic validation and JSON metadata export for XTCE definitions. +//! +//! Goes beyond XML syntax checking to inspect the lowered [`XtceDb`] intermediate representation +//! for dangling references, unsupported constructs, unreachable abstract containers, and static +//! codegen compilability, and optionally exports the normalized mission metadata as JSON. + +use std::io::Write; + +use xtce_model::{DataEncoding, TypeKind, XtceDb}; + +/// Severity of a semantic validation diagnostic. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Level { + /// Prevents correct decoding of at least one container or parameter. + Error, + /// Non-fatal issue (e.g. an abstract container with no inheritors or a dynamic construct + /// that requires interpreted decoding rather than static codegen). + Warning, +} + +/// One semantic diagnostic discovered while validating an [`XtceDb`]. +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct Diagnostic { + pub level: Level, + pub subject: String, + pub message: String, +} + +/// Summary of validating an [`XtceDb`]. +#[derive(Clone, Debug, Default)] +pub struct ValidationReport { + pub diagnostics: Vec, + pub compilable_containers: Option, +} + +impl ValidationReport { + /// Count of [`Level::Error`] diagnostics. + #[must_use] + pub fn error_count(&self) -> usize { + self.diagnostics + .iter() + .filter(|d| d.level == Level::Error) + .count() + } + + /// Count of [`Level::Warning`] diagnostics. + #[must_use] + pub fn warning_count(&self) -> usize { + self.diagnostics + .iter() + .filter(|d| d.level == Level::Warning) + .count() + } +} + +/// CLI options for `xtce validate`. +pub struct Options<'a> { + pub root: Option<&'a str>, + pub json: bool, + pub strict: bool, +} + +/// Runs `xtce validate` on `db` and emits either a text report or JSON metadata dictionary. +/// +/// # Errors +/// +/// Returns an error if I/O fails, if semantic errors are present, or if `strict` is set and +/// warnings are present. +pub fn run(db: &XtceDb, opts: &Options<'_>) -> Result<(), Box> { + let report = validate_db(db, opts.root); + let mut stdout = std::io::stdout().lock(); + if opts.json { + write_json_metadata(&mut stdout, db, &report)?; + } else { + write_text_report(&mut stdout, db, &report)?; + } + if report.error_count() > 0 { + return Err(format!("validation failed with {} error(s)", report.error_count()).into()); + } + if opts.strict && report.warning_count() > 0 { + return Err(format!( + "strict validation failed with {} warning(s)", + report.warning_count() + ) + .into()); + } + Ok(()) +} + +/// Performs semantic validation on `db` and tests static codegen compilability from `root`. +#[must_use] +pub fn validate_db(db: &XtceDb, root: Option<&str>) -> ValidationReport { + let mut report = ValidationReport::default(); + + for unsup in db.unsupported() { + push_unsupported_construct( + &mut report.diagnostics, + &unsup.path, + &unsup.element, + unsup.reason, + ); + } + + for param in db.parameters() { + check_parameter(db, param, &mut report.diagnostics); + } + + for container in db.containers() { + if container.is_abstract && container.inheritors.is_empty() { + push_diag( + &mut report.diagnostics, + Level::Warning, + db.name(container.name), + "abstract container has no inheritors (dead branch)", + ); + } + } + + let opts = xtce_codegen::Options { + root: root.map(str::to_owned), + source_label: None, + }; + match xtce_codegen::plan(db, &opts) { + Ok(plan) => { + report.compilable_containers = Some(plan.containers.len()); + } + Err(err) => { + push_codegen_warning(&mut report.diagnostics, &err); + } + } + + report +} + +fn check_parameter(db: &XtceDb, param: &xtce_model::Parameter, diagnostics: &mut Vec) { + let name = db.name(param.name); + let Some(ty) = db.parameter_type(param.type_id) else { + push_diag( + diagnostics, + Level::Error, + name, + "parameter type index does not resolve", + ); + return; + }; + + if let TypeKind::Unsupported { element } = ty.kind { + push_unsupported_type(diagnostics, name, db.name(element)); + } + if matches!(ty.encoding, DataEncoding::None) + && !matches!(ty.kind, TypeKind::Array { .. } | TypeKind::Aggregate { .. }) + { + push_diag( + diagnostics, + Level::Error, + name, + "parameter type has no data encoding", + ); + } +} + +fn push_diag(diagnostics: &mut Vec, level: Level, subject: &str, message: &str) { + diagnostics.push(Diagnostic { + level, + subject: subject.to_owned(), + message: message.to_owned(), + }); +} + +fn push_unsupported_construct( + diagnostics: &mut Vec, + path: &str, + element: &str, + reason: &str, +) { + diagnostics.push(Diagnostic { + level: Level::Error, + subject: path.to_owned(), + message: format!("unsupported construct <{element}>: {reason}"), + }); +} + +fn push_unsupported_type(diagnostics: &mut Vec, name: &str, element: &str) { + diagnostics.push(Diagnostic { + level: Level::Error, + subject: name.to_owned(), + message: format!("unsupported parameter type <{element}>"), + }); +} + +fn push_codegen_warning(diagnostics: &mut Vec, err: &xtce_codegen::CodegenError) { + diagnostics.push(Diagnostic { + level: Level::Warning, + subject: "codegen".to_owned(), + message: format!("interpreted-only definition ({err})"), + }); +} + +/// Writes the validation report in human-readable text format. +/// +/// # Errors +/// +/// Returns an I/O error if writing fails. +pub fn write_text_report( + out: &mut impl Write, + db: &XtceDb, + report: &ValidationReport, +) -> std::io::Result<()> { + for diag in &report.diagnostics { + let tag = match diag.level { + Level::Error => "ERROR", + Level::Warning => "WARN ", + }; + writeln!(out, "{tag} {}: {}", diag.subject, diag.message)?; + } + + let stats = db.stats(); + let codegen_status = report.compilable_containers.map_or_else( + || "interpreted-only".to_owned(), + |n| format!("static-codegen ready ({n} concrete container(s))"), + ); + + writeln!( + out, + "VALIDATED {} parameter(s), {} container(s), {} command(s) — {} error(s), {} warning(s) [{codegen_status}]", + stats.parameters, + stats.containers, + stats.meta_commands, + report.error_count(), + report.warning_count(), + ) +} + +/// Writes a normalized JSON metadata export of `db` and `report` to `out`. +/// +/// # Errors +/// +/// Returns an I/O error if writing fails. +pub fn write_json_metadata( + out: &mut impl Write, + db: &XtceDb, + report: &ValidationReport, +) -> std::io::Result<()> { + let stats = db.stats(); + writeln!(out, "{{")?; + writeln!(out, " \"parameters_count\": {},", stats.parameters)?; + writeln!(out, " \"containers_count\": {},", stats.containers)?; + writeln!(out, " \"commands_count\": {},", stats.meta_commands)?; + writeln!(out, " \"errors_count\": {},", report.error_count())?; + writeln!(out, " \"warnings_count\": {},", report.warning_count())?; + writeln!( + out, + " \"static_codegen_ready\": {},", + report.compilable_containers.is_some() + )?; + writeln!(out, " \"containers\": [")?; + let containers = db.containers(); + for (idx, c) in containers.iter().enumerate() { + let comma = if idx + 1 < containers.len() { "," } else { "" }; + writeln!( + out, + " {{\"name\": {:?}, \"abstract\": {}, \"entries\": {}}}{comma}", + db.name(c.name), + c.is_abstract, + c.entries.len() + )?; + } + writeln!(out, " ]")?; + writeln!(out, "}}") +} + +#[cfg(test)] +mod tests { + use xtce_model::XtceDb; + + use super::{validate_db, write_json_metadata, write_text_report}; + use crate::pus::ECSS_PUS_XTCE_XML; + + #[test] + fn valid_ecss_pus_definition_passes_with_zero_errors_and_static_codegen_ready() { + let db = XtceDb::from_xml(ECSS_PUS_XTCE_XML).expect("loads"); + let report = validate_db(&db, None); + + assert_eq!(report.error_count(), 0); + assert_eq!(report.compilable_containers, Some(9)); + + let mut text = Vec::new(); + write_text_report(&mut text, &db, &report).expect("writes text"); + let text_str = String::from_utf8(text).expect("utf8"); + assert!(text_str.contains("0 error(s)")); + assert!(text_str.contains("static-codegen ready (9 concrete container(s))")); + + let mut json = Vec::new(); + write_json_metadata(&mut json, &db, &report).expect("writes json"); + let json_str = String::from_utf8(json).expect("utf8"); + assert!(json_str.contains("\"static_codegen_ready\": true")); + assert!(json_str.contains("\"TM_3_25_ObcHousekeeping\"")); + } +} diff --git a/docs/AUDIT_AND_ADR_2027.md b/docs/AUDIT_AND_ADR_2027.md new file mode 100644 index 0000000..0e7ba02 --- /dev/null +++ b/docs/AUDIT_AND_ADR_2027.md @@ -0,0 +1,325 @@ +# Audyt Repozytorium, Rejestr Decyzji Architektonicznych (ADR) oraz Macierz Pokrycia XTCE 1.2 (2027) + +> **Status dokumentu:** Zatwierdzony (Baseline Architektoniczny 2027) +> **Repozytorium:** `RustSpaceLab/xtce-rs` (wersja workspace `0.2.1`, Rust Edition `2024`, MSRV `1.85`) +> **Zakres:** Zadania 1, 2, 3, 4 i 5 z planu *RustSpaceLab Roadmap & Architektura 2027* + +--- + +## 1. Zadanie 1: Audyt Repozytorium (`crates/*` oraz `xtask`) + +### 1.1. Podsumowanie struktury Workspace i poszczególnych Crates + +Główny plik `Cargo.toml` (linie `1–48`) definiuje workspace z `resolver = "3"`, `edition = "2024"` oraz `rust-version = "1.85"`. Członkami workspace są `crates/*` oraz `xtask`, z celowym wykluczeniem `crates/xtce-py` (`exclude = ["crates/xtce-py"]`, linia `7`), aby `cargo build --workspace` nie wymagało obecności biblioteki `libpython` na maszynach CI testujących czysty łańcuch narzędziowy Rust. + +| Crate / Moduł | Ścieżka | Typ | Środowisko (`std`/`no_std`) | Zależności produkcyjne (`[dependencies]`) | Liczba testów `#[test]` | +|---|---|---|---|---|---| +| **`xtce-model`** | `crates/xtce-model` | `lib` | `std` | `quick-xml = "0.38"`, `thiserror = "2"` | **46** (7 unit + 39 integr.) | +| **`xtce-decode`** | `crates/xtce-decode` | `lib` | `std` | `xtce-model`, `thiserror = "2"` | **74** (34 unit + 40 integr.) | +| **`xtce-codegen`** | `crates/xtce-codegen` | `lib` (emituje kod `core`/`no_std`) | `std` (generator) / `core` (wyjście) | `xtce-model`, `thiserror = "2"`, `proc-macro2 = "1"`, `quote = "1"`, `prettyplease = "0.2"`, `syn = "2"` | **15** (1 unit + 14 integr.) | +| **`xtce-codegen-e2e`** | `crates/xtce-codegen-e2e` | `lib` (`publish = false`) | `std` | `[build-dependencies]`: `xtce-model`, `xtce-codegen`; `[dev-dependencies]`: `xtce-model`, `xtce-decode` | **19** (19 integr. E2E) | +| **`xtce-pus`** | `crates/xtce-pus` | `lib` | **`#![no_std]`** (zero alokacji) | **Brak (`0` zależności zewnętrznych)** | **9** (9 unit/HIL) | +| **`xtce-cli`** | `crates/xtce-cli` | `bin` (`xtce`) | `std` | `xtce-model`, `xtce-decode`, `xtce-codegen`, `xtce-pus`, `clap = "4"` (`derive`) | **38** (38 unit) | +| **`xtce-py`** | `crates/xtce-py` | `cdylib` (`xtce`, osobny workspace) | `std` + CPython ABI3 | `xtce-model`, `xtce-decode`, `pyo3 = "0.28"` (`abi3-py310`, `extension-module`) | **14** uruchomień `pytest` (6 funkcji + 2×4 parametryzacji) | +| **`xtask`** | `xtask` | `bin` (`publish = false`) | `std` | `xtce-model`, `xtce-decode`, `serde_json = "1"`, `clap = "4"` | **12** (12 unit) | + +*Łączna liczba testów Rust (`#[test]` w workspace):* **213 testów** (+ 5 doc-testów + 14 przypadków testowych `pytest` w `crates/xtce-py/tests/test_against_reference.py` oraz 18 zestawów referencyjnych *golden files* weryfikowanych przez `cargo xtask diff`). + +--- + +### 1.2. Publiczne API poszczególnych Crates + +#### 1.2.1. `xtce-model` (`crates/xtce-model/src/lib.rs`) +* **Główny punkt wejścia (IR bazy telemetrycznej i telekomend):** + * `XtceDb` (`crates/xtce-model/src/db.rs:35`): `XtceDb::from_path(path)` (linia `114`), `XtceDb::from_xml(text)` (linia `132`), `source()`, `xmlns()`, `skipped_sections()`, `unsupported()`, `interner()`, `name(NameId)`, `space_systems()`, `types()`, `parameters()`, `containers()`, `entries()`, `meta_commands()`, `meta_command(MetaCommandId)`, `fixed_value(Span)`, `find_meta_command(&str)`, `root_containers()`, `space_system(SpaceSystemId)`, `parameter(ParamId)`, `parameter_type(TypeId)`, `container(ContainerId)`, `container_entries(ContainerId)`, `type_of(ParamId)`, `find_parameter(&str)`, `find_container(&str)`, `find_type(&str)`, `boolean_label(TypeId, bool)`, `default_root_container()`, `stats() -> Stats`. + * **Silnie typowane identyfikatory aren (`crates/xtce-model/src/ids.rs`):** `SpaceSystemId`, `TypeId`, `ParamId`, `ContainerId`, `MetaCommandId`, `Span`. + * **Interner napisów (`crates/xtce-model/src/intern.rs`):** `Interner`, `NameId`. + * **Reprezentacja typów i kodowań (`crates/xtce-model/src/types.rs`):** `Parameter`, `ParameterType`, `TypeKind` (`Integer`, `Float`, `Enumerated`, `Boolean`, `String`, `Binary`, `AbsoluteTime`, `RelativeTime`, `Array`, `Aggregate`, `Unsupported`), `DataEncoding` (`Integer`, `Float`, `String`, `Binary`, `None`), `IntegerEncoding`, `IntegerCoding`, `FloatEncoding`, `FloatCoding`, `StringEncoding`, `StringDelimiter`, `Charset`, `BinaryEncoding`, `ByteOrder`, `SizeSpec` (`Fixed`, `Dynamic`, `DiscreteLookup`, `Unsupported`), `LinearAdjustment`, `DiscreteLookup`, `EnumerationList`, `Enumeration`, `Calibrator` (`Polynomial`, `Spline`, `Unsupported`), `ContextCalibrator`, `PolynomialTerm`, `Spline`, `SplinePoint`, `ArrayDimension`, `AggregateMember`. + * **Kontenery i kryteria (`crates/xtce-model/src/containers.rs`):** `SpaceSystem`, `Container`, `Entry`, `EntryKind` (`Parameter`, `Container`, `FixedValue`, `Unsupported`), `Location`, `LocationReference`, `MatchCriteria` (`Comparison`, `Boolean`, `Unsupported`), `Comparison`, `ComparisonValue`, `CompareOp`, `BooleanExpr` (`Condition`, `And`, `Or`), `Condition`, `Operand`. + * **Telekomendy (`crates/xtce-model/src/commands.rs`):** `MetaCommand`. + * **Drzewo DOM XML (`crates/xtce-model/src/xml.rs`):** `Dom`, `Element`, `Node`, `Children`, `Tag`, `AttrKey`. + * **Błędy i diagnostyka (`crates/xtce-model/src/error.rs`):** `XtceError` (`#[non_exhaustive]`), `ParseError`, `RefKind`, `Unsupported`, `Stats`. + +#### 1.2.2. `xtce-decode` (`crates/xtce-decode/src/lib.rs`) +* **Interpreter pakietów (`crates/xtce-decode/src/decoder.rs`):** + * `Decoder<'db>` (linia `31`): `Decoder::new(&'db XtceDb)` (linia `49`), `Decoder::with_root(&'db XtceDb, &str)` (linia `63`), `db()`, `root()`, `decode<'p>(&self, data: &'p [u8]) -> Result, DecodeError>` (linia `102`), `decode_into<'p>(&self, packet: &mut DecodedPacket<'db, 'p>, data: &'p [u8]) -> Result<(), DecodeError>` (linia `132`), `new_packet<'p>(&self, data: &'p [u8]) -> DecodedPacket<'db, 'p>` (linia `195`). +* **Ramkowanie CCSDS Space Packet (`crates/xtce-decode/src/ccsds.rs`):** + * `PRIMARY_HEADER_BYTES` (`6`), `SpacePacketBytes<'a>` (metody: `new`, `bytes`, `version`, `packet_type`, `secondary_header_flag`, `apid`, `sequence_flags`, `sequence_count`, `data_length`, `user_data`). + * `PacketIter<'a>` (linia `131`): bezalokacyjny iterator po wycinku `&'a [u8]` z obsługą `skip_header_bytes`. + * `PacketReader` (linia `242`): strumieniowy czytnik z dowolnego źródła `std::io::Read` z reużywalnym buforem wewnętrznym (`next_packet(&mut self)`). + * Błędy ramkowania: `FramingError` (`ShortHeader`, `ShortPacket`), `PacketReadError` (`Framing`, `Io`). +* **Wartości i kursor bitowy (`crates/xtce-decode/src/value.rs`, `bits.rs`, `error.rs`):** + * `DecodedPacket<'db, 'p>`, `ParameterValue<'db, 'p>`, `RawValue<'p>` (`Unsigned(u64)`, `Signed(i64)`, `Float(f64)`, `Bytes(Cow<'p, [u8]>)`), `EngValue<'db, 'p>` (`Unsigned(u64)`, `Signed(i64)`, `Float(f64)`, `Bool(bool)`, `Label(&'db str)`, `Text(Cow<'p, str>)`, `Bytes(Cow<'p, [u8]>)`). + * `BitCursor<'a>`, `BitError`, `DecodeError` (`#[non_exhaustive]`). + +#### 1.2.3. `xtce-codegen` (`crates/xtce-codegen/src/lib.rs`) +* **Generator statycznych dekoderów Rust (`crates/xtce-codegen/src/lib.rs`):** + * `generate(db: &XtceDb, options: &Options) -> Result` (linia `100`). + * `plan(db: &XtceDb, options: &Options) -> Result` (linia `125`). + * `Options` (`root: Option`, `source_label: Option`), `CodegenError` (`NoSuchContainer`, `AmbiguousRoot`, `Unsupported`, `DanglingIndex`). +* **Planer układu bitowego (`crates/xtce-codegen/src/plan.rs`):** + * `Plan`, `Node`, `ContainerPlan`, `Field`, `FixedBits`, `Guard`, `GuardTest`, `Criterion`, `Calibration`, `ContextCalibration`, `Repr`, `TextCharset`, `TextDelimiter`, `Width`, `plan::build(db, root)`, `field_ident(&str)`, `type_ident(&str)`. +* **Właściwości generowanego kodu (`crates/xtce-codegen/src/emit.rs`):** + * Wygenerowany moduł używa wyłącznie biblioteki `core` (kompatybilny z `#![no_std]`, w tym własna implementacja `powi` oraz `integer_power`), nie zawiera ani jednego bloku `unsafe`, a sprawdzanie granic tablic eliminuje poprzez jednokrotne zawężenie wycinka do tablicy stałego rozmiaru `&[u8; N]` (`emit.rs:466–482`). + +#### 1.2.4. `xtce-pus` (`crates/xtce-pus/src/lib.rs`) +* **`#![no_std]` implementacja ECSS-E-ST-70-41C (PUS-C) oraz OBC HIL Responder:** + * **Ramkowanie (`packet.rs`):** `PusPacket<'a>::parse(&'a [u8])`, `PusHeader` (`Telemetry`, `Telecommand`), `AckFlags`, `CucTimestamp`, `TmParams`, `TcParams`, `encode_tm`, `encode_tc`, `PusError`. + * **Usługi PUS (`services.rs`):** `PusService` (`ST[01]` Verification, `ST[03]` Housekeeping, `ST[05]` Event Reporting, `ST[06]` Memory Management, `ST[08]` Function Management, `ST[11]` Time-Based Scheduling, `ST[12]` On-Board Monitoring, `ST[17]` Test, `ST[20]` Parameter Management), `ObcHousekeeping`. + * **Bezpieczeństwo telekomend (`security.rs`):** `TcSecurityGate` (`new`, `last_counter`, `verify_and_strip`), `compute_mac_tag` (SipHash-2-4, 64-bit MAC), `build_auth_trailer` (12-bajtowy trailer: 4B licznik anty-replay + 8B MAC), `SecurityError` (`MissingTrailer`, `ReplayAttack`, `InvalidMacTag`). + * **Symulator OBC HIL (`hil.rs`):** `PusResponder` (`new`, `with_security_key`, `tick_second`, `process_telecommand`). + * **Suma kontrolna (`crc.rs`):** `crc16_ccitt`, `verify_crc16_ccitt`. + +#### 1.2.5. `xtce-cli` (`crates/xtce-cli/src/main.rs`) +* Narzędzie wiersza poleceń `xtce` z 11 podkomendami (`Command` enum): + 1. `xtce info [--verbose]` (`src/info.rs`) + 2. `xtce decode [--root] [--skip-header-bytes] [--limit] [--param] [--format table|jsonl|csv] [--raw] [--no-summary]` (`src/decode.rs`) + 3. `xtce codegen [--root] [--out]` (`src/main.rs`) + 4. `xtce wireshark [--root] [--out] [--udp-port]` (`src/wireshark.rs` — generator dysektora Lua dla Wireshark) + 5. `xtce pcap [--out] [--skip-header-bytes] [--limit]` (`src/pcap.rs` — opakowanie strumienia CCSDS w `DLT_USER0` `.pcap`) + 6. `xtce encode [--root] [--set NAME=VAL] [--out] [--hex] [--crc]` (`src/encode.rs` — koder pakietów TM/TC z definicji XTCE) + 7. `xtce pus [packets] [--hil-demo] [--hil-udp ADDR] [--emit-xtce] [--out] [--skip-header-bytes] [--limit]` (`src/pus.rs`) + 8. `xtce bench [--iterations]` (`src/main.rs`) + 9. `xtce diff [--root] [--fail-on-breaking]` (`src/diff.rs` — Zadanie 4: Semantic Diff MVP dla definicji XTCE) + 10. `xtce validate [--root] [--json] [--strict]` (`src/validate.rs` — Zadanie 3: Walidator semantyczny i eksporter kanonicznego słownika JSON) + 11. `xtce sim [--scenario nominal|voltage-drop|overheat|comm-loss|reboot] [--packets N] [--seed S] [--pcap] [--out]` (`src/sim.rs` — Zadanie 5: Deterministyczny symulator telemetrii z wstrzykiwaniem awarii) + +#### 1.2.6. `xtce-py` (`crates/xtce-py/src/lib.rs`) +* Moduł natywny Python (`#[pymodule] fn xtce`, `abi3-py310`): + * Klasa `xtce.Definition(path)` (linia `95`): `Definition.from_string(xml)`, właściwości `source`, `parameter_count`, `container_count`, metody `parameter_names()`, `container_names()`, `unsupported()`, `decode_stream(data, *, skip_header_bytes=0, root=None, raw=false, skip_unrecognized=false)` (zwalnia GIL przez `py.detach`, linia `202`), `decode(data, *, root=None, raw=false)`, `container_of_each(data, *, skip_header_bytes=0, root=None)`. + +--- + +### 1.3. Limity Bezpieczeństwa, Ochrona Pamięci i Obsługa Encji XML + +W całym kodzie bibliotecznym i wykonywalnym wymuszono dyrektywy kompilatora: +`#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)]` oraz `#![deny(clippy::todo, clippy::unimplemented)]`. + +| Mechanizm / Stała | Wartość | Dokładna lokalizacja (plik i linia) | Cel i działanie ochronne | +|---|---|---|---| +| **`MAX_EXPANDED_FIELDS`** *(limit liści tablicy/agregatu, odpowiednik `MAX_ARRAY_LEAVES`)* | `4096` (`usize`) | `crates/xtce-model/src/lower.rs:2258` (egzekwowane w `lower.rs:1641–1648`) | Chroni przed bombami kombinatorycznymi podczas rozwijania wielowymiarowych `` i ``. Przekroczenie zwraca `XtceError::ArrayNotExpanded`. Dodatkowo w `lower.rs:1601–1609` iloczyn wymiarów używa `checked_mul`, chroniąc przed przepełnieniem `usize`. | +| **`MAX_CONTAINER_DEPTH`** / **`MAX_DEPTH`** | `64` (`usize`) | `crates/xtce-decode/src/decoder.rs:25` (egzekwowane w `decoder.rs:211`, `924`, `960`) oraz `crates/xtce-codegen/src/plan.rs:482` (egzekwowane w `plan.rs:562`, `629`) | Chroni przed cyklicznymi referencjami `` oraz zbyt głębokimi drzewami dziedziczenia kontenerów, zamieniając przepełnienie stosu (`stack overflow`) na kontrolowany błąd `DecodeError::Unsupported` / `CodegenError::Unsupported`. | +| **Detekcja cykli dziedziczenia i typów** | Trójkolorowe znakowanie / stos odwiedzin | `crates/xtce-model/src/lower.rs:2366–2413` (`check_acyclic`), `lower.rs:598–618` (`resolve_command_bases`), `lower.rs:1557–1566` (`Lowering::enter`) | Wykrywa cykle w ``, `` oraz rekurencyjnych typach `` / `` na etapie ładowania pliku (`XtceError::InheritanceCycle` / `XtceError::ArrayNotExpanded`). | +| **`MAX_DEFINITION_BYTES`** | `256 * 1024 * 1024` (`256 MiB`) | `crates/xtce-cli/src/main.rs:281` oraz `crates/xtce-cli/src/decode.rs:45` | Ogranicza rozmiar dokumentu XTCE wczytywanego ze standardowego wejścia (`stdin.take(MAX_DEFINITION_BYTES)`), zapobiegając wyczerpaniu pamięci RAM (OOM) przy nieskończonym strumieniu. | +| **`MAX_HIL_FRAME_LEN`** & **`OBC_SCRATCHPAD_LEN`** | `64` B / `256` B | `crates/xtce-pus/src/hil.rs:13`, `:16` | Stałe bufory stosowe dla `#![no_std]` symulatora pokładowego OBC, gwarantujące deterministyczny rozmiar ramki i pamięci roboczej dla `ST[06]`. | +| **Obsługa encji XML i odrzucanie DTD / XXE** | Brak ekspansji encji DTD, ignorowanie `Event::DocType` | `crates/xtce-model/src/xml.rs:358–444` oraz `xml.rs:771–795` (`push_entity`) | Parser `quick-xml` działa na pojedynczej arenie tekstowej `String`. Zdarzenie `Event::DocType(_)` jest całkowicie ignorowane (`xml.rs:443`). W `Event::GeneralRef` funkcja `push_entity` (`xml.rs:771–795`) rozwija **wyłącznie** referencje znakowe (`&#...;`, `entity.is_char_ref()`) oraz 5 predefiniowanych encji XML (`amp`, `lt`, `gt`, `apos`, `quot`). Wszelkie inne encje (np. zadeklarowane w DTD) są zapisywane dosłownie jako `&nazwa;` (`xml.rs:789–793`), co całkowicie eliminuje podatności typu *Billion Laughs* (XML Entity Expansion) oraz *XXE*. | +| **Pomijanie nieużywanych sekcji XML w locie** | `Tag::is_skipped_section` | `crates/xtce-model/src/xml.rs:202–212` oraz `xml.rs:381–401`, `465–468` | Sekcje `ServiceSet`, `MessageSet`, `StreamSet`, `AlgorithmSet`, `AliasSet`, `AncillaryDataSet` są odrzucane w pętli zdarzeń SAX przed alokacją węzłów w arenie `Dom`, co chroni pamięć przed nadmiarowymi metadanymi. | + +--- + +### 1.4. Przepływy CI/CD (`.github/workflows/*`) + +1. **`ci.yml` (`.github/workflows/ci.yml:1–102`):** + * **`check` (bramka blokująca, linie `12–43`):** Przypięty toolchain `1.93.1` (`dtolnay/rust-toolchain@1.93.1`), weryfikacja `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, testy jednostkowe i integracyjne `cargo test --workspace` oraz testy różnicowe `cargo run -p xtask --release -- diff`. + * **`latest` (advisory, linie `44–56`):** Clippy na najnowszym `stable` z `continue-on-error: true`. + * **`python` (advisory, linie `58–94`):** Python `3.12`, instalacja `space_packet_parser` z przypiętego commita `6de220ff25e75d0a8b6258086f9d99ce9eae820b`, budowa koła przez `maturin build --release` dla `crates/xtce-py/Cargo.toml` i testy różnicowe `pytest crates/xtce-py/tests -q`. + * **`msrv` (bramka blokująca, linie `95–102`):** Weryfikacja kompatybilności wstecznej z Rust `1.85.0` (`cargo check --workspace`). +2. **`release.yml` (`.github/workflows/release.yml:1–93`):** Budowa binariów `xtce-cli` na tagach `v*` dla `x86_64-unknown-linux-gnu`, `x86_64-apple-darwin` i `aarch64-apple-darwin`, `strip`, pomiar rozmiaru i publikacja GitHub Release (wymaga ręcznie przygotowanych notatek w `docs/releases/v*.md`). +3. **`publish.yml` (`.github/workflows/publish.yml:1–43`):** Publikacja na `crates.io` w porządku topologicznym: `xtce-pus` -> `xtce-model` -> `xtce-decode` -> `xtce-codegen` -> `xtce-cli`. +4. **`pypi.yml` (`.github/workflows/pypi.yml:1–56`):** Budowa kół Python (`abi3-py310`) na Linux, macOS i Windows oraz publikacja na PyPI przez `maturin upload`. + +--- + +## 2. Zadanie 2: Rejestr Decyzji Architektonicznych (ADR 001–005) + +### ADR-001: Kanoniczna reprezentacja pośrednia (Canonical IR) oparta na płaskich arenach w `xtce-model` + +* **Status:** Zaakceptowany (Zaimplementowany w `crates/xtce-model`) +* **Kontekst:** Dokumenty XTCE 1.2 w misjach kosmicznych (np. CTIM: 1,6 MB XML, ~46 000 elementów, 9493 parametrów, 38 kontenerów) zawierają dwukierunkowe referencje ścieżkowe (``, ``, ``) oraz typy złożone (tablice wielowymiarowe i agregaty). Tradycyjne podejście oparte na drzewach `Rc>` lub `Box` generuje dziesiątki tysięcy drobnych alokacji sterty, uniemożliwia współdzielenie modelu między wątkami i zmusza każdy komponent (interpreter, generator kodu, koder TC, generator Lua Wireshark) do osobnej implementacji rozwiązywania nazw, rozwijania tablic i obsługi telekomend. +* **Decyzja:** + 1. Wprowadzamy dwufazowy proces ładowania w `xtce-model`: najpierw lekki, bezalokacyjny dla węzłów parser `xml::Dom` oparty na pojedynczej arenie tekstowej (`crates/xtce-model/src/xml.rs:291–303`), który jest zwalniany natychmiast po zakończeniu fazy obniżania (*lowering*). + 2. Fazę `Lowering` (`crates/xtce-model/src/lower.rs:71–201`) dzielimy na Przebieg 1 (rejestracja przestrzeni nazw `SpaceSystem`, typów, parametrów, kontenerów i telekomend ``) oraz Przebieg 2 (rozwiązywanie referencji do 32-bitowych indeksów `TypeId`, `ParamId`, `ContainerId`, `MetaCommandId`). + 3. Typy złożone (``, ``) są rozwijane w trakcie ładowania (`lower.rs:1454–1654`) do płaskich parametrów liści (`ARR[0]`, `P.voltage`) z twardym limitem `MAX_EXPANDED_FIELDS = 4096`. + 4. Telekomendy (``, ``, ``) są obniżane do tych samych struktur `Container` i `MatchCriteria` co telemetria (`lower.rs:1249–1251`, `1719–1759`), z wydzieloną przestrzenią nazw dla `` (`lower.rs:97–101`). + 5. Wynikowy obiekt `XtceDb` (`crates/xtce-model/src/db.rs:35`) jest niemutowalny, przechowuje wszystkie encje w płaskich wektorach `Vec` oraz jednym `Interner`, i implementuje `Send + Sync`. +* **Konsekwencje:** + * *Pozytywne:* Błyskawiczne ładowanie dużych baz (rzędu kilku milisekund dla 1,6 MB XML), pełna przyjazność dla pamięci podręcznej procesora (cache locality), brak specjalnych ścieżek dla tablic i telekomend w `xtce-decode` oraz `xtce-codegen`. + * *Kompromisy:* Wymiary tablic zależne od zawartości pakietu (`DynamicValue` w `StartingIndex`/`EndingIndex`) nie mogą zostać rozwinięte w czasie ładowania i są jawnie raportowane jako `Unsupported` (`lower.rs:788–796`). + +--- + +### ADR-002: Granice Crates oraz warstwowanie `#![no_std]` / `std` + +* **Status:** Zaakceptowany (Zaimplementowany w całym repozytorium) +* **Kontekst:** Narzędzia naziemne (stacje EGSE, analiza strumieni CCSDS, integracja z Pythonem i Wiresharkiem) wymagają bogatego ekosystemu `std` (system plików, wielowątkowość, CLI, parsowanie XML), podczas gdy oprogramowanie pokładowe (OBC na mikrokontrolerach Cortex-M `thumbv7em-none-eabihf`, RISC-V, LEON/SPARC) oraz wygenerowane statyczne dekodery pakietów muszą działać w rygorystycznym środowisku `#![no_std]` bez alokatora sterty (`alloc`). +* **Decyzja:** + 1. **Warstwa `#![no_std]` czasu wykonania (Flight & Embedded Core):** + * Crate `xtce-pus` (`crates/xtce-pus/src/lib.rs:16`) jest w 100% `#![no_std]`, nie posiada żadnych zależności zewnętrznych (`Cargo.toml:14`) i nie wykonuje żadnych alokacji sterty (wszystkie operacje ramkowania PUS-C, CRC-16-CCITT, bramki kryptograficznej `TcSecurityGate` SipHash-2-4 oraz symulatora `PusResponder` operują na buforach przekazanych przez wywołującego). + * Kod źródłowy Rust generowany przez `xtce-codegen` (`crates/xtce-codegen/src/emit.rs:83–209`) odwołuje się wyłącznie do przestrzeni `core::*` (np. `core::fmt::Display`, `core::error::Error`, własna funkcja `powi`), pożycza bufory tekstowe i binarne bezpośrednio z wycinka pakietu (`&'a str`, `&'a [u8]`) i nie wymaga `std` ani `alloc`. + 2. **Warstwa `std` czasu analizy i narzędzi naziemnych (Ground & Tooling):** + * `xtce-model` (parser XML i budowa IR), `xtce-decode` (dynamiczny interpreter z obsługą transkodowania UTF-16/UTF-32/Latin-1 przez `Cow`), `xtce-codegen` (kompilator definicji używający `syn`/`quote`/`prettyplease`) oraz `xtce-cli` korzystają z `std`. + 3. **Izolacja wiązań FFI (`xtce-py`):** + * `crates/xtce-py` jest wykluczony z głównego workspace (`Cargo.toml:7`) i stanowi osobny workspace (`crates/xtce-py/Cargo.toml:4`), dzięki czemu kompilacja i testy workspace Rust nigdy nie zależą od nagłówków CPython. +* **Konsekwencje:** + * *Pozytywne:* Ten sam kod protokołu PUS-C (`xtce-pus`) oraz wygenerowane przez `xtce-codegen` dekodery mogą być kompilowane bezpośrednio do firmware'u satelity (np. misje PIAST/CAMILA) oraz używane na ziemi w `xtce-cli`. + * *Kompromisy:* Konstrukcje XTCE wymagające alokacji podczas dekodowania (np. nieobrównane do bajtu napisy lub kodowania UTF-16/UTF-32 wymagające transkodowania) są obsługiwane przez interpreter `xtce-decode` (`Cow::Owned`), ale świadomie odrzucane przez `xtce-codegen` (`crates/xtce-codegen/src/plan.rs:738–748`, `1285–1290`), aby nie wprowadzać alokacji na ścieżkę krytyczną `no_std`. + +--- + +### ADR-003: Strumieniowy `PacketReader` kontra bezkopiowy (zero-copy) `PacketIter<'a>` + +* **Status:** Zaakceptowany (Zaimplementowany w `crates/xtce-decode/src/ccsds.rs` oraz `crates/xtce-cli/src/decode.rs`) +* **Kontekst:** Strumienie telemetrii CCSDS 133.0-B trafiają do dekodera w dwóch fundamentalnie różnych scenariuszach: + 1. *Przetwarzanie buforów w pamięci* (np. pliki zmapowane w pamięci, pojedyncze okna odbiorcze w `xtce-py` `decode_stream`, testy jednostkowe i benchmarki), gdzie kluczowa jest praca bez kopiowania bajtów (*zero-copy*). + 2. *Przetwarzanie wielogigabajtowych archiwów lub potoków na żywo* (`stdin`, gniazda TCP/UDP, duże pliki na dysku w `xtce decode` / `xtce pcap`), gdzie wczytanie całego strumienia przez `std::fs::read` doprowadziłoby do wyczerpania pamięci RAM. +* **Decyzja:** + Udostępniamy w module `xtce_decode::ccsds` (`crates/xtce-decode/src/ccsds.rs`) dwa komplementarne mechanizmy ramkowania zwracające ten sam typ widoku `SpacePacketBytes<'_>`: + 1. **`PacketIter<'a>` (`ccsds.rs:131–201`):** Przyjmuje wycinek `&'a [u8]` i `skip_header_bytes: usize`. Nie alokuje pamięci — każdy kolejny `SpacePacketBytes<'a>` jest bezpośrednim podwycinkiem bufora wejściowego. Współpracuje z `Decoder::decode_into(&mut packet, bytes)` (`decoder.rs:132`), co pozwala zdekodować cały strumień przy **zerowej liczbie alokacji** po pierwszym pakiecie. + 2. **`PacketReader` (`ccsds.rs:242–389`):** Opakowuje dowolny czytnik `R: std::io::Read`, pomija `skip_header_bytes`, wczytuje 6-bajtowy nagłówek główny CCSDS, oblicza długość pakietu `6 + C + 1` i doczytuje resztę ramki do pojedynczego, reużywalnego bufora `Vec` (maksymalnie ~64 KiB dla najdłuższego pakietu CCSDS). + 3. Oba interfejsy traktują ucięty ogon strumienia (niepełny nagłówek lub mniej bajtów niż zadeklarowano w polu `C`) jako jawny błąd `FramingError::ShortHeader` / `FramingError::ShortPacket`, zamiast po cichu kończyć iterację (`ccsds.rs:175–196`, `338–373`). +* **Konsekwencje:** + * *Pozytywne:* `xtce-cli` (`crates/xtce-cli/src/decode.rs` oraz `pcap.rs`) przetwarza dowolnie duże pliki i potoki `stdin` w stałej pamięci $O(1)$ za pomocą `PacketReader>`, podczas gdy `xtce-py` i `xtask diff` osiągają maksymalną przepustowość w pamięci dzięki `PacketIter`. + * *Kompromisy:* `PacketReader::next_packet(&mut self)` zwraca `SpacePacketBytes<'_>` pożyczający z wewnętrznego bufora czytnika (*lending iterator pattern*), dlatego nie implementuje standardowego traitu `Iterator` (który w Rust nie obsługuje pożyczek z `self` bez GAT). + +--- + +### ADR-004: Taksonomia błędów bez ścieżek paniki (No-Panic Error Taxonomy) + +* **Status:** Zaakceptowany (Zaimplementowany we wszystkich crates) +* **Kontekst:** Dekoder telemetrii i odbiornik telekomend pracują na żywym łączu radiowym (downlink/uplink), gdzie uszkodzone ramki, zakłócenia RF lub złośliwie spreparowane pakiety są zjawiskiem normalnym. Wywołanie `panic!`, `unwrap()` lub `expect()` na poziomie biblioteki oznaczałoby awarię całego procesu stacji naziemnej lub reset komputera pokładowego OBC. Równocześnie użytkownik ładujący bazę XTCE, która w 95% składa się ze wspieranych konstrukcji, a w 5% używa rzadkich elementów (np. ``), musi móc załadować bazę i zdekodować wszystkie pakiety nieużywające tego elementu. +* **Decyzja:** + 1. **Bezwzględny zakaz paniki w kodzie bibliotecznym i CLI:** Wszystkie crates wymuszają `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)]` oraz `#![deny(clippy::todo, clippy::unimplemented)]`. Dostęp do wycinków i aren odbywa się wyłącznie przez bezpieczne metody `.get(...)` z propagacją `Result` lub niejawnym węzłem zastępczym (`DETACHED` w `xml.rs:590`). + 2. **Trójpoziomowa semantyka wsparcia XTCE (`SUPPORTED.md:7–17`):** + * *Decodable:* Pełny model w IR i pełne dekodowanie. + * *Represented:* Konstrukcja jest parsowana do wariantu `Unsupported` w IR (`TypeKind::Unsupported`, `EntryKind::Unsupported`, `SizeSpec::Unsupported`, `Calibrator::Unsupported`, `MatchCriteria::Unsupported`) i rejestrowana na liście `XtceDb::unsupported()`. Ładowanie pliku przez `XtceDb::from_xml` **kończy się sukcesem**, a błąd `DecodeError::Unsupported { element, context }` jest zgłaszany *dopiero wtedy*, gdy dekodowany pakiet faktycznie natrafi na dany element. + * *Rejected (Load-Time Fatal):* Błędy strukturalne uniemożliwiające bezpieczną budowę IR (np. uszkodzony XML, cykl dziedziczenia kontenerów `XtceError::InheritanceCycle`, nierozwiązana referencja `XtceError::UnresolvedReference`, nieudane rozwinięcie tablicy `XtceError::ArrayNotExpanded`, które przesunęłoby offsety wszystkich kolejnych pól) przerywają ładowanie natychmiast. + 3. **Rozdzielona hierarchia typów błędów dla każdej warstwy:** + * `xtce_model::XtceError` (`#[non_exhaustive]`, `crates/xtce-model/src/error.rs:9`) + `ParseError` z dokładnym offsetem bajtowym w XML. + * `xtce_decode::DecodeError` (`#[non_exhaustive]`, `crates/xtce-decode/src/error.rs:14`) + `BitError` + `FramingError` + `PacketReadError`. + * `xtce_codegen::CodegenError` (`#[non_exhaustive]`, `crates/xtce-codegen/src/lib.rs:63`): odmawia kompilacji niewspieranej konstrukcji **z podaniem jej nazwy i kontenera** (nigdy nie wykonuje cichego fallbacku do interpretera). + * `xtce_pus::PusError` (`crates/xtce-pus/src/packet.rs:24`) oraz `SecurityError` (`security.rs:25`): lekkie typy `Copy + PartialEq + Eq` kompatybilne z `core::error::Error` w `#![no_std]`. +* **Konsekwencje:** + * *Pozytywne:* Odporność na fuzzing (`proptest` w `xtce-decode/src/bits.rs`) i uszkodzone strumienie; możliwość inspekcji dowolnej bazy misyjnej komendą `xtce info` oraz walidacji komendą `xtce validate` przed uruchomieniem dekodera. + * *Kompromisy:* Kod wewnętrzny musi jawnie obsługiwać warianty `DecodeError::DanglingIndex` / `CodegenError::DanglingIndex` zamiast używać indeksowania `vec[i]`. + +--- + +### ADR-005: Potok Walidacji, Semantic Diff (`xtce diff`) i Testów Różnicowych (Three-Rung Validation Pipeline) + +* **Status:** Zaakceptowany (Zaimplementowany w `xtask`, `xtce-codegen-e2e`, `xtce-py` oraz `xtce-cli/src/{diff,validate,sim}.rs`) +* **Kontekst:** Standard XTCE 1.2 zawiera liczne niejednoznaczności (np. kolejność sumowania wyrazów wielomianu kalibratora zmiennoprzecinkowego, traktowanie bitów wysuniętych poza szerokość pola przy odwracaniu kolejności bajtów `leastSignificantByteFirst`, porównywanie `NaN` w kryteriach wyboru kontenera). Równocześnie w cyklu życia misji kosmicznej (Faza B/C/D) definicje XTCE ewoluują między zespołami FSW i Ground Segment — przypadkowa zmiana rozmiaru pola z 16 na 32 bity przesuwa wszystkie kolejne pola w pakiecie o 16 bitów, czego zwykły `git diff` na plikach XML nie potrafi wykryć. +* **Decyzja:** + 1. **Trójstopniowy potok weryfikacji różnicowej (*Three-Rung Differential Pipeline*):** + * **Stopień 1: Interpreter Rust (`xtce-decode`) vs Referencja Python (`space_packet_parser` @ `6de220ff`) przez `cargo xtask diff` (`xtask/src/diff.rs`):** Weryfikuje 18 zestawów testowych (*golden files* w `testdata/golden/*.json`), łącząc porównanie szczegółowe (parametr po parametrze dla pierwszych 64 pakietów) ze skrótem SHA-256 (`xtask/src/sha256.rs`) liczonego po kanonicznej serializacji wszystkich pakietów w strumieniu. + * **Stopień 2: Statyczny Generator Kodu (`xtce-codegen`) vs Interpreter Rust (`xtce-decode`) w `xtce-codegen-e2e` (`crates/xtce-codegen-e2e/tests/against_interpreter.rs`):** Skrypt `build.rs` kompiluje wszystkie 18 definicji XTCE do statycznych modułów Rust i porównuje je bit-po-bicie (`to_bits()` dla `f64`) z interpreterem. + * **Stopień 3: Wiązania Python (`xtce-py`) vs `space_packet_parser` (`crates/xtce-py/tests/test_against_reference.py`):** Weryfikuje granicę FFI PyO3 oraz zwalnianie blokady GIL (`py.detach`). + 2. **Semantic Diff (`xtce diff [--fail-on-breaking]`, `crates/xtce-cli/src/diff.rs`):** + * Porównuje dwie bazy na poziomie kanonicznego IR (`XtceDb`) oraz spłaszczonego planu bitowego (`xtce_codegen::Plan`), klasyfikując każdą zmianę jako `BREAKING` (usunięcie parametru/kontenera, zmiana typu/szerokości/znaku/endianness, usunięcie lub zmiana wartości enuma, przesunięcie `bit_offset` w kontenerze), `WARNING` (dodanie nowej wartości enuma lub pola na końcu kontenera) albo `COMPATIBLE` (dodanie nowego niezależnego parametru lub kontenera). + 3. **Walidator semantyczny i eksporter JSON (`xtce validate [--json] [--strict]`, `crates/xtce-cli/src/validate.rs`) oraz deterministyczny symulator misji (`xtce sim`, `crates/xtce-cli/src/sim.rs`):** + * `xtce validate` weryfikuje spójność IR, martwe gałęzie abstrakcyjnych kontenerów i gotowość do kompilacji `xtce-codegen`, oraz eksportuje znormalizowany słownik metadanych do JSON. + * `xtce sim` generuje powtarzalne strumienie CCSDS / ECSS PUS-C (z ziarnem SplitMix64 `--seed`) dla scenariuszy `nominal`, `voltage-drop`, `overheat`, `comm-loss`, `reboot`. +* **Konsekwencje:** + * *Pozytywne:* Gwarancja zgodności bitowej między wygenerowanym kodem `#![no_std]`, interpreterem Rust oraz referencyjnym parserem LASP Python, połączona z bramką CI (`xtce diff --fail-on-breaking` i `xtce validate --strict`) chroniącą przed niekompatybilnymi zmianami formatu ramek. + +--- + +## 3. Zadanie 3: Macierz Pokrycia i Walidacji XTCE 1.2 (Evidence-Backed Matrix) + +Poniższa macierz zestawia pełne pokrycie standardu **OMG XTCE 1.2 (CCSDS 660.1-G-2)** z dokładnymi dowodami w kodzie źródłowym: +* **`crates/xtce-model/src/lower.rs`** (oraz `xml.rs` dla sekcji pomijanych), +* **`crates/xtce-decode/src/decoder.rs`** (oraz moduły pomocnicze `calibrate.rs`, `charset.rs`, `bits.rs`), +* **`crates/xtce-codegen/src/plan.rs`** (oraz `emit.rs`), +* **`SUPPORTED.md`**. + +### Legenda kategorii pokrycia +1. **Wspierane w Interpreterze i Static Codegen (`Interpreter + Codegen`)** — konstrukcja w pełni zamodelowana w IR, dekodowana przez `xtce-decode` i kompilowana do statycznego kodu Rust przez `xtce-codegen`. +2. **Wspierane tylko w Interpreterze (`Tylko Interpreter / Częściowe w Codegen`)** — konstrukcja w pełni dekodowana przez `xtce-decode`, natomiast `xtce-codegen` świadomie odmawia jej kompilacji (`CodegenError::Unsupported`), np. ze względu na brak wyrównania do bajtu, konieczność alokacji przy transkodowaniu lub przesunięcia bitowe `LocationInContainerInBits`. +3. **Częściowo wspierane / Reprezentowane w IR (`Represented / Partial`)** — konstrukcja jest parsowana i obecna w IR (`XtceDb::unsupported()`), dzięki czemu plik XTCE ładuje się poprawnie, ale próba zdekodowania parametru od niej zależnego zwraca `DecodeError::Unsupported` (lub wybrane atrybuty pomocnicze nie są aplikowane w arytmetyce). +4. **Niewspierane / Odrzucane (`Unsupported / Rejected`)** — sekcja pomijana na etapie parsera XML (`skipped_sections`) lub powodująca błąd ładowania `XtceError` (np. dynamiczny wymiar tablicy). + +--- + +### 3.1. Sekcje główne dokumentu `` + +| Konstrukcja XTCE 1.2 | Status pokrycia | `xtce-model` (`xml.rs` / `lower.rs`) | `xtce-decode` (`decoder.rs`) | `xtce-codegen` (`plan.rs`) | `SUPPORTED.md` | +|---|---|---|---|---|---| +| `SpaceSystem` (hierarchia i referencje ścieżkowe `/`, `.`, `..`) | **Interpreter + Codegen** | `lower.rs:151–158`, `205–265`, `1937–2012`, `2134–2164` | `decoder.rs:49–78` | `plan.rs:458–471` | `L21–24` | +| `TelemetryMetaData` (`ParameterTypeSet`, `ParameterSet`, `ContainerSet`) | **Interpreter + Codegen** | `lower.rs:240–256` | `decoder.rs:102–192` | `plan.rs:555–618` | `L23` | +| `CommandMetaData` (`ArgumentTypeSet`, `MetaCommandSet`, `CommandContainerSet`) | **Interpreter + Codegen** | `lower.rs:258–316` | `decoder.rs:102–192` (wspólna maszyneria kontenerów) | `plan.rs:555–699` | `L24`, `L28–50`, `L181–185` | +| `ServiceSet`, `MessageSet`, `StreamSet`, `AlgorithmSet` | **Rejected (Skipped)** | `xml.rs:202–212`, `465–468` (pomijane w locie, zapisywane w `skipped_sections`) | — | — | `L25` | +| `AliasSet`, `AncillaryDataSet` | **Rejected (Skipped)** | `xml.rs:202–212`, `465–468` | — | — | `L26` | + +--- + +### 3.2. Telekomendy (``) + +| Konstrukcja XTCE 1.2 | Status pokrycia | `xtce-model` (`lower.rs`) | `xtce-decode` (`decoder.rs`) | `xtce-codegen` (`plan.rs`) | `SUPPORTED.md` | +|---|---|---|---|---|---| +| `MetaCommand` (w tym `abstract="true"`) | **Interpreter + Codegen** | `lower.rs:363–468`, `634–639`, `1276–1281`, `1762–1796` | `decoder.rs:176–184` (respektuje `is_abstract`) | `plan.rs:580–601` | `L37`, `L181` | +| `BaseMetaCommand` (dziedziczenie, detekcja cykli) | **Interpreter + Codegen** | `lower.rs:572–631` (`resolve_command_bases`) | `decoder.rs:141–187` | `plan.rs:555–618` | `L38`, `L181` | +| `ArgumentList`, `Argument` (kwalifikowane pod komendą `/SS/Cmd/ARG`) | **Interpreter + Codegen** | `lower.rs:394–423`, `1169–1192`, `1703–1709` | `decoder.rs:278–306` | `plan.rs:703–836` | `L39`, `L181` | +| `ArgumentAssignmentList`, `ArgumentAssignment` (w tym na wyliczeniach `Enumerated`) | **Interpreter + Codegen** | `lower.rs:1249–1251`, `1719–1759` (`use_calibrated: true`) | `decoder.rs:720–806` | `plan.rs:510–529`, `1337–1361`, `1478–1508` (`GuardTest::Labels`) | `L40`, `L50`, `L182–183` | +| `CommandContainer` oraz `CommandContainerSet` | **Interpreter + Codegen** | `lower.rs:298–308`, `426–457` (`is_command: true`) | `decoder.rs:204–275` | `plan.rs:555–699` | `L41`, `L47`, `L181` | +| `ArgumentRefEntry`, `ArrayArgumentRefEntry` | **Interpreter + Codegen** | `lower.rs:1359–1416` (`lower_argument_lookup`) | `decoder.rs:244–246` | `plan.rs:684–697` | `L42`, `L181` | +| `FixedValueEntry` (`binaryValue`, `sizeInBits`) | **Interpreter + Codegen** (w Codegen wymagany stały offset) | `lower.rs:1306–1333`, `1417` | `decoder.rs:255–265` (`cursor.skip`) | `plan.rs:243–259`, `490–504`, `654–676` (odrzuca po dynamicznej szerokości: `plan.rs:660–667`) | `L44`, `L119`, `L184–185` | +| `*ArgumentType` (`Integer`, `Float`, `String`, `Binary`, `Boolean`, `Enumerated`, `AbsoluteTime`, `Array`, `Aggregate`) | **Interpreter + Codegen** | `lower.rs:280–288`, `320–353`, `506–533`, `673–713` | `decoder.rs:308–377` | `plan.rs:1103–1183` | `L45–46` | +| `RelativeTimeArgumentType` | **Represented (Partial)** | `lower.rs:705–707` (`TypeKind::RelativeTime`) | `decoder.rs:342` (dekoduje surowe bity jeśli ma kodowanie, brak arytmetyki epoki) | **Refused:** `plan.rs:1176–1181` | `L45`, `L63` | +| `BlockMetaCommand`, `VerifierSet`, `TransmissionConstraintList`, `Interlock`, `ParameterToSetList` | **Rejected** | Nierozpoznawane jako definicje pakietów (`xml.rs:48`, `lower.rs:269–316`) | — | — | `L48–49` | + +--- + +### 3.3. Typy Parametrów (``) + +| Konstrukcja XTCE 1.2 | Status pokrycia | `xtce-model` (`lower.rs`) | `xtce-decode` (`decoder.rs`) | `xtce-codegen` (`plan.rs`) | `SUPPORTED.md` | +|---|---|---|---|---|---| +| `IntegerParameterType` (1–64 bity: `unsigned`, `twosComplement`/`twosCompliment`/`signed`, `signMagnitude`, `onesComplement`) | **Interpreter + Codegen** (w Codegen i Interpreterze odrzucane LE signed 57–63 bity niepodzielne przez 8) | `lower.rs:674`, `912–918`, `2228–2237` | `decoder.rs:453–486` (błąd dla 57–63b LE `twosComplement`: `decoder.rs:471–481`) | `plan.rs:759–784`, `1117`, `1242–1252` (odrzuca 57–63b LE signed: `plan.rs:775–784`) | `L56`, `L114`, `L149`, `L155` | +| `FloatParameterType` — IEEE-754 (`16`, `32`, `64` bity) | **Interpreter + Codegen** | `lower.rs:675`, `919–925`, `2239–2244` | `decoder.rs:488–505`, `1115–1150` (`half_to_f32` z subnormalnymi i zachowaniem NaN payload) | `plan.rs:1117`, `1253–1263` (inne szerokości odrzucane: `plan.rs:1258–1263`) | `L57`, `L126`, `L150` | +| `FloatParameterType` — `MILSTD_1750A` / `MIL-1750A` (`32` bity) | **Interpreter + Codegen** (szerokości $\neq 32$ odrzucane) | `lower.rs:2239–2244` | `decoder.rs:512–519`, `1156–1161` (odrzuca $\neq 32$ bity: `decoder.rs:512–517`) | `plan.rs:31–36`, `1264–1272` (odrzuca $\neq 32$ bity: `plan.rs:1267–1272`) | `L57`, `L190–191`, `L237–242` | +| `EnumeratedParameterType` (`EnumerationList`, `Enumeration`, zakresy `maxValue`) | **Interpreter + Codegen** (Codegen wymaga kodowania całkowitoliczbowego) | `lower.rs:686–688`, `860–897` | `decoder.rs:348–362` | `plan.rs:1129–1148` (odrzuca enum na kodowaniu float: `plan.rs:1130–1135`) | `L58`, `L120`, `L151` | +| `BooleanParameterType` (`zeroStringValue`, `oneStringValue`) | **Interpreter + Codegen** | `lower.rs:678–685` (`db.rs:319–329` `boolean_label`) | `decoder.rs:363–371` | `plan.rs:1118` | `L59`, `L151` | +| `StringParameterType` (UTF-8, US-ASCII, wyrównane do bajtu, `Fixed` / `DynamicValue`, `TerminationChar`, `LeadingSize`) | **Interpreter + Codegen** | `lower.rs:676`, `926–928`, `951–1012` | `decoder.rs:326–340`, `543–629` | `plan.rs:730–748`, `1152–1160`, `1280–1306` | `L60`, `L170`, `L174` | +| `StringParameterType` — niewyrównane do granicy bajtu, `DiscreteLookupList`, lub kodowania `ISO-8859-1`, `Windows-1252`, `UTF-16*`, `UTF-32*` | **Tylko Interpreter** (Refused w Codegen) | `lower.rs:956–964`, `1059–1071`, `2278–2287` | `decoder.rs:558–564`, `621–628` (`crates/xtce-decode/src/charset.rs`) | **Refused:** `plan.rs:738–744` (brak wyrównania), `plan.rs:1226–1229` (`DiscreteLookup`), `plan.rs:1284–1290` (transkodowanie) | `L60`, `L73`, `L172–173` | +| `BinaryParameterType` (wyrównane do bajtu, `Fixed` lub `DynamicValue` + `LinearAdjustment`) | **Interpreter + Codegen** | `lower.rs:677`, `929–931`, `1014–1057` | `decoder.rs:523–532`, `631–693` | `plan.rs:730–748`, `1161–1169`, `1307–1311` | `L61`, `L171`, `L174` | +| `BinaryParameterType` — niewyrównane do granicy bajtu lub rozmiar z `DiscreteLookupList` | **Tylko Interpreter** (Refused w Codegen) | `lower.rs:1059–1071` | `decoder.rs:523–532`, `679`, `695–716` | **Refused:** `plan.rs:738–744`, `plan.rs:1226–1229` (w runtime dla dynamicznej szerokości: `DecodeError::Unaligned`, `emit.rs:133–139`) | `L61`, `L76`, `L172`, `L176` | +| `AbsoluteTimeParameterType` (`Encoding` z `offset`/`scale`, `ReferenceTime`/`Epoch`/`OffsetFrom`) | **Partial (Interpreter + Codegen)** — `offset` i `scale` przeliczane jako kalibrator wielomianowy; `Epoch` i `OffsetFrom` zamodelowane w IR, ale nieprzeliczane na datę | `lower.rs:666`, `689–704`, `2192–2226` (`apply_time_unit_scaler`) | `decoder.rs:375` (przez wygenerowany kalibrator wielomianowy) | `plan.rs:1117` | `L62` | +| `RelativeTimeParameterType` | **Represented (Partial)** — zamodelowany w IR, odrzucany w Codegen | `lower.rs:705–707` | `decoder.rs:342` (brak arytmetyki epoki) | **Refused:** `plan.rs:1176–1181` | `L63` | +| `ArrayParameterType` (stałe `StartingIndex` / `EndingIndex`, rozwijane do liści `ARR[i][j]` w porządku row-major do 4096 pól) | **Interpreter + Codegen** | `lower.rs:708–710`, `761–814`, `1454–1654`, `2258` | `decoder.rs:244–246` (widzi rozwinięte parametry skalarne) | `plan.rs:684–697` (odrzuca nierozwiniętą tablicę: `plan.rs:1123–1128`) | `L64`, `L177–180`, `L217–226` | +| `ArrayParameterType` z wymiarem odczytywanym z pakietu (`DynamicValue` / `DiscreteLookupList` w `Dimension`) | **Represented / Rejected** (`TypeKind::Unsupported` na typie, `XtceError::ArrayNotExpanded` na subsettingu wpisu) | `lower.rs:788–796` (na typie), `lower.rs:1486–1496` (na wpisie) | `decoder.rs:315–320` (`DecodeError::Unsupported`) | **Refused:** `plan.rs:1123–1128`, `1170–1175` | `L64`, `L178` | +| `AggregateParameterType` (`MemberList`, `Member`, rozwijane do `P.member`, zagnieżdżenia z tablicami) | **Interpreter + Codegen** | `lower.rs:711–713`, `817–858`, `1454–1654` | `decoder.rs:244–246` | `plan.rs:684–697` | `L65`, `L177`, `L217–226` | + +--- + +### 3.4. Kodowania Danych (``) i Rozmiary (``) + +| Konstrukcja XTCE 1.2 | Status pokrycia | `xtce-model` (`lower.rs`) | `xtce-decode` (`decoder.rs`) | `xtce-codegen` (`plan.rs`) | `SUPPORTED.md` | +|---|---|---|---|---|---| +| `IntegerDataEncoding` / `FloatDataEncoding` — `byteOrder="mostSignificantByteFirst"` oraz `"leastSignificantByteFirst"` | **Interpreter + Codegen** | `lower.rs:912–925`, `2271–2276` | `decoder.rs:461–479`, `496–498` (`swap_byte_order`) | `plan.rs:199–205`, `1240–1278` (`emit.rs:658–663`) | `L71–72`, `L154–155`, `L243–255` | +| `StringDataEncoding` (`Fixed`, `Variable`/`DynamicValue`, `TerminationChar`, `LeadingSize`) | **Interpreter + Codegen** (Codegen: tylko UTF-8 i US-ASCII wyrównane do bajtu) | `lower.rs:951–1012` | `decoder.rs:543–629` | `plan.rs:1280–1306` | `L73`, `L170–174` | +| `BinaryDataEncoding` (`SizeInBits/Fixed`, `DynamicValue`, `DiscreteLookupList`) | **Interpreter + Codegen** (Codegen: bez `DiscreteLookupList` i tylko wyrównane do bajtu) | `lower.rs:929–931`, `1014–1076` | `decoder.rs:523–532`, `631–716` | `plan.rs:1187–1232`, `1307–1311` | `L74–76`, `L171–176` | +| `SizeInBits/DynamicValue` + `LinearAdjustment` (`slope`, `intercept`) | **Interpreter + Codegen** (w Codegen tylko dla pól tekstowych i binarnych) | `lower.rs:1038–1057`, `2304–2315` | `decoder.rs:640–677` | `plan.rs:751–758` (odrzuca zmienną szerokość pola liczbowego), `1195–1225` | `L75`, `L174–175` | +| `SizeInBits/DiscreteLookupList` (`DiscreteLookup`) | **Tylko Interpreter** (Refused w Codegen) | `lower.rs:1059–1071` | `decoder.rs:679`, `695–716` | **Refused:** `plan.rs:1226–1229` | `L76` | +| `ErrorDetectCorrect` | **Rejected (Ignored)** | Ignorowane podczas obniżania kodowania (`lower.rs:899–934`) | — | — | `L77` | + +--- + +### 3.5. Kontenery (``) i Kryteria Wyboru (``) + +| Konstrukcja XTCE 1.2 | Status pokrycia | `xtce-model` (`lower.rs`) | `xtce-decode` (`decoder.rs`) | `xtce-codegen` (`plan.rs`) | `SUPPORTED.md` | +|---|---|---|---|---|---| +| `SequenceContainer`, `EntryList`, `ParameterRefEntry` | **Interpreter + Codegen** | `lower.rs:1214–1299`, `1358–1416` | `decoder.rs:141–192`, `204–275` | `plan.rs:555–699` | `L82–83` | +| `ContainerRefEntry` (rozwijane inline, limit głębokości 64) | **Interpreter + Codegen** | `lower.rs:1418–1434` | `decoder.rs:211–219`, `247–249` | `plan.rs:629–635`, `649–653` | `L84`, `L124`, `L153` | +| `BaseContainer` + `RestrictionCriteria` (wykrywanie cykli przy ładowaniu) | **Interpreter + Codegen** | `lower.rs:1227–1243`, `2343–2413` | `decoder.rs:149–187`, `720–738` | `plan.rs:603–610`, `1330–1362` | `L85`, `L152` | +| `Comparison`, `ComparisonList` (`==`, `!=`, `<`, `<=`, `>`, `>=`) | **Interpreter + Codegen** (w Codegen: kryteria na liczbach całkowitych oraz etykietach `Enumerated`; odrzucane kryteria na `useCalibratedValue` dla kalibrowanych floatów i `Boolean`) | `lower.rs:1679–1686`, `1798–1820` | `decoder.rs:764–806`, `1054–1075` | `plan.rs:510–529`, `1339–1350`, `1435–1508` (odrzuca `useCalibratedValue` na kalibrowanym parametrze i `Bool`: `plan.rs:1478–1491`) | `L86`, `L152`, `L158–161` | +| `BooleanExpression` (`Condition`, `ANDedConditions`, `ORedConditions`) — parametr vs literał | **Interpreter + Codegen** | `lower.rs:1687–1692`, `1822–1909` | `decoder.rs:808–861` | `plan.rs:1351`, `1365–1429` | `L87`, `L187`, `L257–265` | +| `BooleanExpression` (`Condition`) — parametr vs parametr lub literał po lewej stronie | **Tylko Interpreter** (Refused w Codegen) | `lower.rs:1871–1909` | `decoder.rs:834–892`, `1078–1104` | **Refused:** `plan.rs:1391–1414` | `L87`, `L122`, `L188–189` | +| `LocationInContainerInBits` z `referenceLocation="previousEntry"` lub `"containerStart"` (na wpisach skalarnych) | **Tylko Interpreter** (Refused w Codegen; na wpisach tablicowych/agregatach oznaczane jako `Unsupported`) | `lower.rs:1347`, `1400–1411`, `2048–2061`, `2289–2296` | `decoder.rs:223–240` (`cursor.seek`) | **Refused:** `plan.rs:639–645` | `L88`, `L112`, `L186` | +| `LocationInContainerInBits` z `referenceLocation="containerEnd"` lub `"nextEntry"` | **Represented (Partial)** — ładowane do IR, zgłaszane przy dekodowaniu | `lower.rs:2048–2061`, `2289–2296` | `decoder.rs:227–236` (`DecodeError::Unsupported`) | **Refused:** `plan.rs:639–645` | `L89` | +| `RepeatEntry` ze stałym `Count/FixedValue` (na wpisach skalarnych i `ContainerRefEntry`) | **Tylko Interpreter** (w Codegen wspierane dla `ContainerRefEntry`/`FixedValueEntry`, odrzucane dla `ParameterRefEntry`; na tablicach/agregatach `Unsupported`) | `lower.rs:1348`, `1400–1411`, `2069–2076` | `decoder.rs:242` (`for _ in 0..entry.repeat.unwrap_or(1)`) | **Refused dla parametrów:** `plan.rs:685–693` (wspierane dla `Container`/`FixedValue`: `plan.rs:650`, `659`) | `L90`, `L113`, `L186` | +| `RepeatEntry` z dynamicznym `Count` (`DynamicValue`) | **Represented** (`EntryKind::Unsupported`) | `lower.rs:1353–1356`, `2091–2096` | `decoder.rs:266–271` (`DecodeError::Unsupported`) | **Refused:** `plan.rs:677–683` | `L91` | +| `IncludeCondition` | **Represented** (`EntryKind::Unsupported`) | `lower.rs:1353–1356`, `2085–2090` | `decoder.rs:266–271` (`DecodeError::Unsupported`) | **Refused:** `plan.rs:677–683` | `L92` | +| `IndirectParameterRefEntry` | **Represented** (`EntryKind::Unsupported`) | `lower.rs:1435–1441` | `decoder.rs:266–271` (`DecodeError::Unsupported`) | **Refused:** `plan.rs:677–683` | `L93` | +| `ArrayParameterRefEntry` (w tym subsetting przez `` ze stałymi indeksami) | **Interpreter + Codegen** | `lower.rs:1359–1414`, `1481–1500`, `1569–1595` | `decoder.rs:244–246` | `plan.rs:684–697` | `L94`, `L177` | +| `CustomAlgorithm` w `RestrictionCriteria` lub `ContextMatch` | **Represented** (`MatchCriteria::Unsupported`) | `lower.rs:1693–1695`, `1911–1921` | `decoder.rs:757–760` (`DecodeError::Unsupported`) | **Refused:** `plan.rs:992–995`, `1352–1358` | `L95`, `L169` | + +--- + +### 3.6. Kalibratory (``, ``) + +| Konstrukcja XTCE 1.2 | Status pokrycia | `xtce-model` (`lower.rs`) | `xtce-decode` (`decoder.rs` / `calibrate.rs`) | `xtce-codegen` (`plan.rs` / `emit.rs`) | `SUPPORTED.md` | +|---|---|---|---|---|---| +| `PolynomialCalibrator` (`Term` z `coefficient` i `exponent`) | **Interpreter + Codegen** | `lower.rs:1111–1125` | `decoder.rs:379–443` (`crates/xtce-decode/src/calibrate.rs:41–73`) | `plan.rs:870`, `940` (`emit.rs:769–793`: osobna ścieżka `i128` i `powi`) | `L101`, `L125`, `L156`, `L168`, `L207–215` | +| `SplineCalibrator` (`SplinePoint`, `order="0"` i `order="1"`, `extrapolate="true"\|"false"`) | **Interpreter + Codegen** | `lower.rs:1127–1149` (sortowanie punktów po `raw`: `lower.rs:1138`) | `decoder.rs:379–443` (`calibrate.rs:75–155`) | `plan.rs:871–890`, `941–949` (`emit.rs:794–818`) | `L102`, `L123`, `L157`, `L167` | +| `SplineCalibrator` rzędu `order > 1` lub bez punktów | **Represented (Partial)** — ładowane do IR, odrzucane przy dekodowaniu i planowaniu Codegen | `lower.rs:1127–1149` | `calibrate.rs:80–91` (`DecodeError::Calibration`) | **Refused:** `plan.rs:876–887`, `942–947` | `L167` | +| `ContextCalibratorList` / `ContextCalibrator` (`ContextMatch` z `Comparison` / `ComparisonList` oraz obecnym `DefaultCalibrator`) | **Interpreter + Codegen** | `lower.rs:1083–1106` | `decoder.rs:396–411`, `782–798` | `plan.rs:789–821`, `904–1100` (`emit.rs:747–759`) | `L103`, `L163`, `L228–235` | +| `ContextCalibratorList` bez `DefaultCalibrator`, lub z `BooleanExpression`, lub z `useCalibratedValue="true"` na aktualnie kalibrowanym polu | **Tylko Interpreter** (Refused w Codegen) | `lower.rs:1083–1106` | `decoder.rs:396–425`, `785–790` | **Refused:** `plan.rs:922–929` (brak `DefaultCalibrator`), `plan.rs:987–991` (`BooleanExpression`), `plan.rs:1027–1036` (`useCalibratedValue` na bieżącym polu) | `L164–166` | +| `MathOperationCalibrator` oraz `CustomAlgorithm` jako kalibrator | **Represented** (`Calibrator::Unsupported`) | `lower.rs:1150–1156` | `decoder.rs:433–438` (`DecodeError::Unsupported`) | **Refused:** `plan.rs:891–894`, `950–955` | `L104`, `L169` | From 54fe19d7cb97b26403e5b1c05087c24370fa20fc Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Thu, 19 Nov 2026 14:01:25 +0100 Subject: [PATCH 12/13] feat(cli,docs): add multi-target xtce compile command and attitude-loss/sensor-glitch sim scenarios --- crates/xtce-cli/README.md | 8 + crates/xtce-cli/src/compile.rs | 310 +++++++++++++++++++++++++++++++++ crates/xtce-cli/src/main.rs | 43 +++++ crates/xtce-cli/src/sim.rs | 15 ++ docs/AUDIT_AND_ADR_2027.md | 94 ++++++++-- 5 files changed, 459 insertions(+), 11 deletions(-) create mode 100644 crates/xtce-cli/src/compile.rs diff --git a/crates/xtce-cli/README.md b/crates/xtce-cli/README.md index ce90fe2..2bb6350 100644 --- a/crates/xtce-cli/README.md +++ b/crates/xtce-cli/README.md @@ -52,6 +52,14 @@ $ xtce diff mission_v1.xml mission_v2.xml --fail-on-breaking # 9. Simulate a deterministic CCSDS / ECSS PUS-C telemetry stream (with fault injection) $ xtce sim --scenario voltage-drop --packets 20 --seed 42 -o fault_pass.bin $ xtce sim --scenario overheat --packets 20 --seed 42 --pcap -o overheat_pass.pcap +$ xtce sim --scenario attitude-loss --packets 20 --seed 42 -o adcs_tumble.bin + +# 10. Multi-target XTCE mission compiler (rust-ground, wireshark, json-schema, docs, dashboard) +$ xtce compile ecss_pus.xml --target rust-ground -o decoder.rs +$ xtce compile ecss_pus.xml --target wireshark -o mission.lua +$ xtce compile ecss_pus.xml --target json-schema -o mission.schema.json +$ xtce compile ecss_pus.xml --target docs -o MISSION_DICTIONARY.md +$ xtce compile ecss_pus.xml --target dashboard -o telemetry_studio.json ``` Part of [RustSpaceLab/xtce-rs](https://github.com/RustSpaceLab/xtce-rs). diff --git a/crates/xtce-cli/src/compile.rs b/crates/xtce-cli/src/compile.rs new file mode 100644 index 0000000..fffd4cb --- /dev/null +++ b/crates/xtce-cli/src/compile.rs @@ -0,0 +1,310 @@ +//! `xtce compile` — multi-target XTCE mission compiler. +//! +//! Treats an XTCE 1.2 definition as a single source of truth and compiles it into multiple +//! mission artifacts in one pass: +//! - `rust-ground`: zero-allocation `#![no_std]` static Rust decoder module (`xtce-codegen`). +//! - `wireshark`: standalone Wireshark Lua dissector script (`.lua`). +//! - `json-schema`: JSON Schema (Draft 2020-12) describing decoded telemetry and command packets. +//! - `docs`: Markdown mission dictionary documenting all containers, parameters, types, and +//! telecommands. +//! - `dashboard`: Telemetry Studio JSON dashboard layout and limit-alarm configuration. + +use std::fmt::Write as _; +use std::io::Write; +use std::path::Path; + +use xtce_model::{DataEncoding, TypeKind, XtceDb}; + +use crate::wireshark; + +/// Compilation targets supported by `xtce compile --target `. +#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)] +pub enum Target { + /// Static `#![no_std]` Rust decoder module (`xtce_codegen`). + RustGround, + /// Standalone Wireshark Lua dissector script (`.lua`). + Wireshark, + /// JSON Schema (Draft 2020-12) for decoded telemetry & telecommand packets. + JsonSchema, + /// Markdown mission dictionary of containers, parameters, enumerations, and telecommands. + Docs, + /// Telemetry Studio JSON dashboard and alarm configuration. + Dashboard, +} + +/// Options for `xtce compile`. +pub struct Options<'a> { + pub definition: &'a Path, + pub target: Target, + pub root: Option<&'a str>, + pub out: Option<&'a Path>, +} + +/// Executes `xtce compile` against a loaded [`XtceDb`]. +/// +/// # Errors +/// +/// Returns an error if code generation or writing to the output path fails. +pub fn run_with_db(db: &XtceDb, opts: &Options<'_>) -> Result<(), Box> { + let content = match opts.target { + Target::RustGround => { + let source_label = if opts.definition.as_os_str() == "-" { + Some("".to_owned()) + } else { + Some(opts.definition.display().to_string()) + }; + xtce_codegen::generate( + db, + &xtce_codegen::Options { + root: opts.root.map(str::to_owned), + source_label, + }, + )? + } + Target::Wireshark => { + return wireshark::run_with_db( + db, + &wireshark::Options { + definition: opts.definition, + root: opts.root, + out: opts.out, + udp_port: Some(5006), + }, + ); + } + Target::JsonSchema => emit_json_schema(db), + Target::Docs => emit_markdown_docs(db), + Target::Dashboard => emit_dashboard_config(db), + }; + + match opts.out { + Some(path) if path.as_os_str() != "-" => { + std::fs::write(path, content)?; + eprintln!("compiled {:?} target to {}", opts.target, path.display()); + } + _ => { + let mut stdout = std::io::stdout().lock(); + stdout.write_all(content.as_bytes())?; + } + } + Ok(()) +} + +/// Emits a JSON Schema (Draft 2020-12) describing decoded packets for `db`. +#[must_use] +pub fn emit_json_schema(db: &XtceDb) -> String { + let mut out = String::with_capacity(4096); + let root_ss = db + .space_systems() + .first() + .map_or("Mission", |ss| db.name(ss.name)); + + let _ = writeln!(out, "{{"); + let _ = writeln!( + out, + " \"$schema\": \"https://json-schema.org/draft/2020-12/schema\"," + ); + let _ = writeln!( + out, + " \"title\": \"{root_ss} Telemetry & Command Schema\"," + ); + let _ = writeln!(out, " \"type\": \"object\","); + let _ = writeln!(out, " \"required\": [\"container\", \"parameters\"],"); + let _ = writeln!(out, " \"properties\": {{"); + let _ = writeln!(out, " \"container\": {{"); + let _ = writeln!(out, " \"type\": \"string\","); + let _ = write!(out, " \"enum\": ["); + + let concrete: Vec<&str> = db + .containers() + .iter() + .filter(|c| !c.is_abstract) + .map(|c| db.name(c.name)) + .collect(); + for (idx, name) in concrete.iter().enumerate() { + let sep = if idx + 1 < concrete.len() { ", " } else { "" }; + let _ = write!(out, "{name:?}{sep}"); + } + let _ = writeln!(out, "]"); + let _ = writeln!(out, " }},"); + let _ = writeln!(out, " \"parameters\": {{"); + let _ = writeln!(out, " \"type\": \"object\","); + let _ = writeln!(out, " \"properties\": {{"); + + let params = db.parameters(); + for (idx, param) in params.iter().enumerate() { + let comma = if idx + 1 < params.len() { "," } else { "" }; + let p_name = db.name(param.name); + let json_type = db + .parameter_type(param.type_id) + .map_or("\"string\"", |ty| match ty.kind { + TypeKind::Integer => "\"integer\"", + TypeKind::Float => "\"number\"", + TypeKind::Boolean { .. } => "\"boolean\"", + _ => "\"string\"", + }); + let _ = writeln!( + out, + " {p_name:?}: {{ \"type\": {json_type} }}{comma}" + ); + } + + let _ = writeln!(out, " }}"); + let _ = writeln!(out, " }}"); + let _ = writeln!(out, " }}"); + let _ = writeln!(out, "}}"); + out +} + +/// Emits a Markdown mission reference dictionary for `db`. +#[must_use] +pub fn emit_markdown_docs(db: &XtceDb) -> String { + let mut out = String::with_capacity(4096); + let root_ss = db + .space_systems() + .first() + .map_or("Mission", |ss| db.name(ss.name)); + let stats = db.stats(); + + let _ = writeln!(out, "# {root_ss} — XTCE Mission Data Dictionary\n"); + let _ = writeln!( + out, + "- **Space Systems:** {}\n- **Parameters:** {}\n- **Containers:** {} ({} abstract)\n- **Telecommands:** {}\n", + stats.space_systems, + stats.parameters, + stats.containers, + stats.abstract_containers, + stats.meta_commands + ); + + let _ = writeln!(out, "## 1. Sequence Containers\n"); + let _ = writeln!(out, "| Container | Kind | Base | Entries |"); + let _ = writeln!(out, "|---|---|---|---:|"); + for c in db.containers() { + let name = db.name(c.name); + let kind = if c.is_abstract { + "abstract" + } else if c.is_command { + "command" + } else { + "telemetry" + }; + let base = c + .base + .and_then(|id| db.container(id)) + .map_or("-", |b| db.name(b.name)); + let _ = writeln!( + out, + "| `{name}` | {kind} | `{base}` | {} |", + c.entries.len() + ); + } + + let _ = writeln!(out, "\n## 2. Parameters & Arguments\n"); + let _ = writeln!(out, "| Parameter | Type | Family | Width (bits) |"); + let _ = writeln!(out, "|---|---|---|---:|"); + for p in db.parameters() { + let p_name = db.name(p.name); + if let Some(ty) = db.parameter_type(p.type_id) { + let t_name = db.name(ty.name); + let family = ty.kind.label(); + let bits = ty + .fixed_size_in_bits() + .map_or_else(|| "var".to_owned(), |b| b.to_string()); + let _ = writeln!(out, "| `{p_name}` | `{t_name}` | {family} | {bits} |"); + } + } + + if !db.meta_commands().is_empty() { + let _ = writeln!(out, "\n## 3. Telecommands (``)\n"); + let _ = writeln!(out, "| Telecommand | Abstract | Arguments |"); + let _ = writeln!(out, "|---|---|---:|"); + for cmd in db.meta_commands() { + let name = db.name(cmd.name); + let _ = writeln!( + out, + "| `{name}` | {} | {} |", + cmd.is_abstract, + cmd.arguments.len() + ); + } + } + + out +} + +/// Emits a Telemetry Studio JSON dashboard and alarm configuration for `db`. +#[must_use] +pub fn emit_dashboard_config(db: &XtceDb) -> String { + let mut out = String::with_capacity(2048); + let root_ss = db + .space_systems() + .first() + .map_or("Mission", |ss| db.name(ss.name)); + + let _ = writeln!(out, "{{"); + let _ = writeln!(out, " \"mission\": {root_ss:?},"); + let _ = writeln!(out, " \"theme\": \"orbittrack-dark\","); + let _ = writeln!(out, " \"panels\": ["); + + let numeric_params: Vec<(&str, &str)> = db + .parameters() + .iter() + .filter_map(|p| { + let ty = db.parameter_type(p.type_id)?; + match &ty.encoding { + DataEncoding::Integer(_) | DataEncoding::Float(_) => { + Some((db.name(p.name), ty.kind.label())) + } + _ => None, + } + }) + .collect(); + + for (idx, (p_name, kind)) in numeric_params.iter().enumerate() { + let comma = if idx + 1 < numeric_params.len() { + "," + } else { + "" + }; + let widget = if *kind == "enumerated" { + "status-badge" + } else { + "timeseries-chart" + }; + let _ = writeln!( + out, + " {{\"parameter\": {p_name:?}, \"widget\": {widget:?}}}{comma}" + ); + } + + let _ = writeln!(out, " ]"); + let _ = writeln!(out, "}}"); + out +} + +#[cfg(test)] +mod tests { + use xtce_model::XtceDb; + + use super::{emit_dashboard_config, emit_json_schema, emit_markdown_docs}; + use crate::pus::ECSS_PUS_XTCE_XML; + + #[test] + fn compiles_json_schema_markdown_docs_and_dashboard_config() { + let db = XtceDb::from_xml(ECSS_PUS_XTCE_XML).expect("loads PUS XTCE"); + + let schema = emit_json_schema(&db); + assert!(schema.contains("https://json-schema.org/draft/2020-12/schema")); + assert!(schema.contains("\"TM_3_25_ObcHousekeeping\"")); + assert!(schema.contains("\"OBC_VBUS_V\"")); + + let docs = emit_markdown_docs(&db); + assert!(docs.contains("# ECSS_PUS_EO_Satellite — XTCE Mission Data Dictionary")); + assert!(docs.contains("| `TM_3_25_ObcHousekeeping` | telemetry |")); + + let dash = emit_dashboard_config(&db); + assert!(dash.contains("\"mission\": \"ECSS_PUS_EO_Satellite\"")); + assert!(dash.contains("\"parameter\": \"OBC_TEMP_C\"")); + } +} diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index 4407196..2d2300a 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -19,6 +19,7 @@ use std::time::Instant; use clap::{Parser, Subcommand}; use xtce_model::XtceDb; +mod compile; mod decode; mod diff; mod encode; @@ -102,6 +103,24 @@ enum Command { out: Option, }, + /// Multi-target XTCE mission compiler (rust-ground, wireshark, json-schema, docs, dashboard). + Compile { + /// XTCE definition. Use '-' to read from standard input. + definition: PathBuf, + + /// Artifact target to compile. + #[arg(long, value_enum, default_value_t = compile::Target::RustGround)] + target: compile::Target, + + /// Explicit root container to start from. + #[arg(long)] + root: Option, + + /// Write compiled artifact here instead of standard output. + #[arg(long, short)] + out: Option, + }, + /// Compile a definition into a Wireshark Lua dissector script (.lua). Wireshark { /// XTCE definition. Use '-' to read from standard input. @@ -325,6 +344,12 @@ fn run(cli: Cli) -> Result<(), Box> { root, out, } => run_codegen(&definition, root, out), + Command::Compile { + definition, + target, + root, + out, + } => run_compile(&definition, target, root.as_deref(), out.as_deref()), Command::Wireshark { definition, root, @@ -405,6 +430,24 @@ fn run(cli: Cli) -> Result<(), Box> { } } +fn run_compile( + definition: &Path, + target: compile::Target, + root: Option<&str>, + out: Option<&Path>, +) -> Result<(), Box> { + let db = load_db(definition)?; + compile::run_with_db( + &db, + &compile::Options { + definition, + target, + root, + out, + }, + ) +} + fn run_diff( old: &Path, new: &Path, diff --git a/crates/xtce-cli/src/sim.rs b/crates/xtce-cli/src/sim.rs index e514e20..777a6a8 100644 --- a/crates/xtce-cli/src/sim.rs +++ b/crates/xtce-cli/src/sim.rs @@ -27,6 +27,10 @@ pub enum Scenario { CommLoss, /// On-board watchdog reset mid-pass: uptime and sequence counters reset with a boot event. Reboot, + /// ADCS star-tracker / reaction-wheel tumble: spacecraft drops into SAFE mode with event `0x0504`. + AttitudeLoss, + /// Corrupted sensor readout: injects an out-of-limits telemetry spike and anomaly report `0x0505`. + SensorGlitch, } /// Configuration for `xtce sim`. @@ -118,6 +122,13 @@ pub fn generate_stream(scenario: Scenario, packet_count: usize, seed: u64) -> Ve seq_count = 0; mode = 0; // Boot into SAFE mode } + Scenario::AttitudeLoss if step >= fault_step => { + mode = 0; // ADCS tumble -> enter SAFE mode + } + Scenario::SensorGlitch if step == fault_step + 1 => { + bus_voltage_mv = 35_900; // Spurious ADC spike + obc_temp_cdeg = 8_500; + } _ => {} } @@ -128,6 +139,8 @@ pub fn generate_stream(scenario: Scenario, packet_count: usize, seed: u64) -> Ve Scenario::Overheat => (0x1202, obc_temp_cdeg as u16), Scenario::CommLoss => (0x0502, 17), Scenario::Reboot => (0x0503, 1), + Scenario::AttitudeLoss => (0x0504, 0), + Scenario::SensorGlitch => (0x0505, 0xFFFF), Scenario::Nominal => (0x0000, 0), }; let id_b = ev_id.to_be_bytes(); @@ -244,6 +257,8 @@ mod tests { Scenario::Overheat, Scenario::CommLoss, Scenario::Reboot, + Scenario::AttitudeLoss, + Scenario::SensorGlitch, ] { let stream = generate_stream(scenario, 12, 1337); let mut count = 0usize; diff --git a/docs/AUDIT_AND_ADR_2027.md b/docs/AUDIT_AND_ADR_2027.md index 0e7ba02..6cf274b 100644 --- a/docs/AUDIT_AND_ADR_2027.md +++ b/docs/AUDIT_AND_ADR_2027.md @@ -19,11 +19,11 @@ Główny plik `Cargo.toml` (linie `1–48`) definiuje workspace z `resolver = "3 | **`xtce-codegen`** | `crates/xtce-codegen` | `lib` (emituje kod `core`/`no_std`) | `std` (generator) / `core` (wyjście) | `xtce-model`, `thiserror = "2"`, `proc-macro2 = "1"`, `quote = "1"`, `prettyplease = "0.2"`, `syn = "2"` | **15** (1 unit + 14 integr.) | | **`xtce-codegen-e2e`** | `crates/xtce-codegen-e2e` | `lib` (`publish = false`) | `std` | `[build-dependencies]`: `xtce-model`, `xtce-codegen`; `[dev-dependencies]`: `xtce-model`, `xtce-decode` | **19** (19 integr. E2E) | | **`xtce-pus`** | `crates/xtce-pus` | `lib` | **`#![no_std]`** (zero alokacji) | **Brak (`0` zależności zewnętrznych)** | **9** (9 unit/HIL) | -| **`xtce-cli`** | `crates/xtce-cli` | `bin` (`xtce`) | `std` | `xtce-model`, `xtce-decode`, `xtce-codegen`, `xtce-pus`, `clap = "4"` (`derive`) | **38** (38 unit) | +| **`xtce-cli`** | `crates/xtce-cli` | `bin` (`xtce`) | `std` | `xtce-model`, `xtce-decode`, `xtce-codegen`, `xtce-pus`, `clap = "4"` (`derive`) | **39** (39 unit) | | **`xtce-py`** | `crates/xtce-py` | `cdylib` (`xtce`, osobny workspace) | `std` + CPython ABI3 | `xtce-model`, `xtce-decode`, `pyo3 = "0.28"` (`abi3-py310`, `extension-module`) | **14** uruchomień `pytest` (6 funkcji + 2×4 parametryzacji) | | **`xtask`** | `xtask` | `bin` (`publish = false`) | `std` | `xtce-model`, `xtce-decode`, `serde_json = "1"`, `clap = "4"` | **12** (12 unit) | -*Łączna liczba testów Rust (`#[test]` w workspace):* **213 testów** (+ 5 doc-testów + 14 przypadków testowych `pytest` w `crates/xtce-py/tests/test_against_reference.py` oraz 18 zestawów referencyjnych *golden files* weryfikowanych przez `cargo xtask diff`). +*Łączna liczba testów Rust (`#[test]` w workspace):* **214 testów** (+ 5 doc-testów + 14 przypadków testowych `pytest` w `crates/xtce-py/tests/test_against_reference.py` oraz 18 zestawów referencyjnych *golden files* weryfikowanych przez `cargo xtask diff`). --- @@ -71,18 +71,19 @@ Główny plik `Cargo.toml` (linie `1–48`) definiuje workspace z `resolver = "3 * **Suma kontrolna (`crc.rs`):** `crc16_ccitt`, `verify_crc16_ccitt`. #### 1.2.5. `xtce-cli` (`crates/xtce-cli/src/main.rs`) -* Narzędzie wiersza poleceń `xtce` z 11 podkomendami (`Command` enum): +* Narzędzie wiersza poleceń `xtce` z 12 podkomendami (`Command` enum): 1. `xtce info [--verbose]` (`src/info.rs`) 2. `xtce decode [--root] [--skip-header-bytes] [--limit] [--param] [--format table|jsonl|csv] [--raw] [--no-summary]` (`src/decode.rs`) 3. `xtce codegen [--root] [--out]` (`src/main.rs`) - 4. `xtce wireshark [--root] [--out] [--udp-port]` (`src/wireshark.rs` — generator dysektora Lua dla Wireshark) - 5. `xtce pcap [--out] [--skip-header-bytes] [--limit]` (`src/pcap.rs` — opakowanie strumienia CCSDS w `DLT_USER0` `.pcap`) - 6. `xtce encode [--root] [--set NAME=VAL] [--out] [--hex] [--crc]` (`src/encode.rs` — koder pakietów TM/TC z definicji XTCE) - 7. `xtce pus [packets] [--hil-demo] [--hil-udp ADDR] [--emit-xtce] [--out] [--skip-header-bytes] [--limit]` (`src/pus.rs`) - 8. `xtce bench [--iterations]` (`src/main.rs`) - 9. `xtce diff [--root] [--fail-on-breaking]` (`src/diff.rs` — Zadanie 4: Semantic Diff MVP dla definicji XTCE) - 10. `xtce validate [--root] [--json] [--strict]` (`src/validate.rs` — Zadanie 3: Walidator semantyczny i eksporter kanonicznego słownika JSON) - 11. `xtce sim [--scenario nominal|voltage-drop|overheat|comm-loss|reboot] [--packets N] [--seed S] [--pcap] [--out]` (`src/sim.rs` — Zadanie 5: Deterministyczny symulator telemetrii z wstrzykiwaniem awarii) + 4. `xtce compile [--target rust-ground|wireshark|json-schema|docs|dashboard] [--root] [--out]` (`src/compile.rs` — wielocelowy kompilator misji XTCE) + 5. `xtce wireshark [--root] [--out] [--udp-port]` (`src/wireshark.rs` — generator dysektora Lua dla Wireshark) + 6. `xtce pcap [--out] [--skip-header-bytes] [--limit]` (`src/pcap.rs` — opakowanie strumienia CCSDS w `DLT_USER0` `.pcap`) + 7. `xtce encode [--root] [--set NAME=VAL] [--out] [--hex] [--crc]` (`src/encode.rs` — koder pakietów TM/TC z definicji XTCE) + 8. `xtce pus [packets] [--hil-demo] [--hil-udp ADDR] [--emit-xtce] [--out] [--skip-header-bytes] [--limit]` (`src/pus.rs`) + 9. `xtce bench [--iterations]` (`src/main.rs`) + 10. `xtce diff [--root] [--fail-on-breaking]` (`src/diff.rs` — Zadanie 4: Semantic Diff MVP dla definicji XTCE) + 11. `xtce validate [--root] [--json] [--strict]` (`src/validate.rs` — Zadanie 3: Walidator semantyczny i eksporter kanonicznego słownika JSON) + 12. `xtce sim [--scenario nominal|voltage-drop|overheat|comm-loss|reboot|attitude-loss|sensor-glitch] [--packets N] [--seed S] [--pcap] [--out]` (`src/sim.rs` — Zadanie 5: Deterministyczny symulator telemetrii z wstrzykiwaniem awarii) #### 1.2.6. `xtce-py` (`crates/xtce-py/src/lib.rs`) * Moduł natywny Python (`#[pymodule] fn xtce`, `abi3-py310`): @@ -323,3 +324,74 @@ Poniższa macierz zestawia pełne pokrycie standardu **OMG XTCE 1.2 (CCSDS 660.1 | `ContextCalibratorList` / `ContextCalibrator` (`ContextMatch` z `Comparison` / `ComparisonList` oraz obecnym `DefaultCalibrator`) | **Interpreter + Codegen** | `lower.rs:1083–1106` | `decoder.rs:396–411`, `782–798` | `plan.rs:789–821`, `904–1100` (`emit.rs:747–759`) | `L103`, `L163`, `L228–235` | | `ContextCalibratorList` bez `DefaultCalibrator`, lub z `BooleanExpression`, lub z `useCalibratedValue="true"` na aktualnie kalibrowanym polu | **Tylko Interpreter** (Refused w Codegen) | `lower.rs:1083–1106` | `decoder.rs:396–425`, `785–790` | **Refused:** `plan.rs:922–929` (brak `DefaultCalibrator`), `plan.rs:987–991` (`BooleanExpression`), `plan.rs:1027–1036` (`useCalibratedValue` na bieżącym polu) | `L164–166` | | `MathOperationCalibrator` oraz `CustomAlgorithm` jako kalibrator | **Represented** (`Calibrator::Unsupported`) | `lower.rs:1150–1156` | `decoder.rs:433–438` (`DecodeError::Unsupported`) | **Refused:** `plan.rs:891–894`, `950–955` | `L104`, `L169` | + +--- + +## 4. Uzupełnienie ze strategii `RustSpaceLab` (XTCE Compiler, Telemetry Studio, Interoperacyjność i Rozpoznawalność) + +Poniższa sekcja domyka elementy wizji strategicznej `RustSpaceLab`, które zostały zidentyfikowane w analizie ekosystemowej, a zostały skrócone w pierwotnym dokumencie PDF. + +### 4.1. Wielocelowy kompilator misji (`xtce compile --target `) + +Zgodnie z koncepcją *„Jeden ekosystem. Jeden model danych. Wiele zastosowań”*, pojedynczy plik definicji XTCE 1.2 stanowi źródło prawdy kompilowane z poziomu `xtce-cli` (`crates/xtce-cli/src/compile.rs`) do pięciu artefaktów inżynieryjnych: + +```bash +xtce compile mission.xml --target rust-ground -o decoder.rs +xtce compile mission.xml --target wireshark -o mission.lua +xtce compile mission.xml --target json-schema -o mission.schema.json +xtce compile mission.xml --target docs -o MISSION_DICTIONARY.md +xtce compile mission.xml --target dashboard -o telemetry_studio.json +``` + +*Dla kompilacji pokładowych koderów `#![no_std]` używany jest komplementarny kompilator `xtce-flight` z repozytorium `RustSpaceLab/xtce-flight`, a dla wiązań Python — pakiet `xtce-py`.* + +### 4.2. Rozszerzony Symulator Misji (`xtce sim`) + +Symulator `xtce sim` (`crates/xtce-cli/src/sim.rs`) obsługuje pełen zestaw 7 deterministycznych profili orbitalnych i awaryjnych zasilanych 64-bitowym generatorem SplitMix64 (`--seed`): +1. `nominal` — nominalny przelot orbitalny LEO (28,2 V, 22,5 °C, telemetria `TM[3,25]` i `TM[17,2]`). +2. `voltage-drop` — degradacja / spadek napięcia baterii w cieniu Ziemi poniżej 24,0 V z raportem `TM[5,2]` (`0x1201`) i przejściem do `SAFE_MODE`. +3. `overheat` — przegrzanie komputera pokładowego OBC powyżej +68,0 °C z alarmem `TM[5,2]` (`0x1202`). +4. `comm-loss` — utrata łączności radiowej (skok licznika sekwencji CCSDS o 17 utraconych ramek i raport `0x0502`). +5. `reboot` — reset komputera pokładowego OBC (watchdog reset, wyzerowanie `OBC_UPTIME_S` i raport startowy `0x0503`). +6. `attitude-loss` — utrata orientacji ADCS (tumble / star-tracker fault, raport `0x0504` i natychmiastowe przejście do `SAFE_MODE`). +7. `sensor-glitch` — przekłamanie przetwornika ADC / błędne wartości telemetryczne (pik 35,9 V / 85,0 °C i raport anomalii `0x0505`). + +### 4.3. Interoperacyjność w ekosystemie Rust (`sat-rs`, `spacepackets-rs`, `cfdp-rs`) + +```text + RustSpaceLab + | + +---------+---------+ + | | + xtce-rs xtce-flight + | | + +---------+---------+ + | + CCSDS / ECSS PUS Layer (xtce-pus #![no_std]) + | + +---------+---------+ + | | + spacepackets-rs sat-rs / cfdp-rs + | + xtce-gs + | + Telemetry Studio / OrbitTrack Live Mission Demo +``` + +Zamiast duplikować całe frameworki oprogramowania pokładowego lub protokoły transferu plików: +* `xtce-decode::SpacePacketBytes` oraz `xtce-pus::PusPacket` operują bezpośrednio na surowych wycinkach `&[u8]` CCSDS 133.0-B-2, co pozwala na bezkopiową wymianę ramek z `spacepackets-rs`, `sat-rs` oraz `cfdp-rs`. + +### 4.4. Trzy filary rozpoznawalności i adopcji `RustSpaceLab` + +1. **RustSpaceLab Mission Demo (`OrbitTrack / Telemetry Studio Live`):** + * Publicznie dostępny, interaktywny demonstrator online (wdrożony na żywo pod adresem **`https://altanix.dev/mission-demo`**) połączony z prawdziwym silnikiem Rust (`xtce` + `#![no_std]` `xtce-pus` HIL OBC responder), wizualizujący w czasie rzeczywistym konstelację polskich i europejskich satelitów LEO (`PIAST-M`, `CAMILA-1`, `EagleEye-2`, `OPS-SAT-2`, `PW-Sat3`) na mapie orbitalnej oraz globusie 3D nad stacją naziemną w Warszawie, z żywymi wykresami telemetrii, wstrzykiwaniem awarii, wysyłaniem podpisanych kryptograficznie telekomend ECSS PUS-C (SipHash-2-4 MAC) i inspektorem ramek CCSDS. +2. **Public Performance Lab:** + * Powtarzalne benchmarki (`cargo run -p xtask --release -- diff` oraz `xtce bench`) porównujące przepustowość i czas ładowania definicji (do **103× szybciej przy ładowaniu** i **124× szybciej przy dekodowaniu** niż referencyjny `space_packet_parser` w Pythonie, przy **0 alokacjach na pakiet** w ścieżce `decode_into` oraz `xtce-codegen`). +3. **Space Software Engineering Blog (Seria artykułów technicznych):** + * *Why Rust is interesting for spacecraft software* + * *How to build a zero-allocation XTCE decoder* + * *From XTCE XML to `#![no_std]` machine code without a single panic path* + * *How CCSDS and ECSS PUS-C telemetry decoding works* + * *Testing satellite software without a satellite (Deterministic HIL & Fault Injection)* + * *Deterministic Rust in embedded systems* + From 992ebdd12884045371d4bcb5448aacd4d7582b18 Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Fri, 20 Nov 2026 13:23:16 +0100 Subject: [PATCH 13/13] docs: add live OrbitTrack & PUS-C Mission Demo link to README --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ab865d1..9fe69f8 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,9 @@ Decode CCSDS telemetry packets in Rust, according to an [XTCE](https://www.omg.org/spec/XTCE/) definition. Part of [RustSpaceLab](https://github.com/RustSpaceLab). +🛰️ **Live Interactive Mission Demo (OrbitTrack & ECSS PUS-C Telemetry Studio):** +👉 **[https://altanix.dev/mission-demo/](https://altanix.dev/mission-demo/)** — *Fly 5 live LEO satellites (`PIAST-M`, `CAMILA-1`, `EagleEye-2`, `PW-Sat3`, `OPS-SAT-2`) in 2D/3D orbit, uplink authenticated ECSS-E-ST-70-41C (PUS-C) telecommands over UDP to the `#![no_std]` OBC responder, inject orbital faults (`xtce sim`), and run `xtce diff` / `validate` / `codegen` / `wireshark` live in your browser.* + The reference implementation in this niche, [`lasp/space_packet_parser`][spp], has a known performance problem: on real mission databases, loading the XTCE file costs more than parsing the packets ([issue #112][issue112]). This project attacks both halves — a fast XML-to-IR @@ -19,7 +22,7 @@ validated against that same implementation packet for packet. | [`xtce-decode`](https://crates.io/crates/xtce-decode) | IR + `&[u8]` / `PacketReader` → parameter values | | [`xtce-codegen`](https://crates.io/crates/xtce-codegen) | IR → a static Rust decoder with every offset baked in | | [`xtce-pus`](https://crates.io/crates/xtce-pus) | `#![no_std]` ECSS-E-ST-70-41C (PUS-C) framing, CRC-16-CCITT, and HIL OBC responder | -| [`xtce-cli`](https://crates.io/crates/xtce-cli) | `xtce info`, `xtce decode`, `xtce codegen`, `xtce wireshark`, `xtce pcap`, `xtce pus`, `xtce bench` | +| [`xtce-cli`](https://crates.io/crates/xtce-cli) | `xtce info`, `xtce decode`, `xtce codegen`, `xtce compile`, `xtce wireshark`, `xtce pcap`, `xtce encode`, `xtce pus`, `xtce diff`, `xtce validate`, `xtce sim`, `xtce bench` | | `xtce-py` | Python bindings (PyO3), built by `maturin` | | `xtask` | differential test harness against the Python reference |