From 0015847ac0ecf559ff5eb78ceea693a6683808ce Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Fri, 20 Nov 2026 23:46:21 +0100 Subject: [PATCH] feat(compile,wasm): add C99/Python compile targets and browser HIL TC encoder --- README.md | 2 +- crates/xtce-cli/README.md | 14 +- crates/xtce-cli/src/compile.rs | 308 ++++++++++++++++++++++++++++++++- crates/xtce-cli/src/main.rs | 2 +- crates/xtce-wasm/src/lib.rs | 221 ++++++++++++++++++++++- 5 files changed, 536 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 0e28a87..8a778cf 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ validated against that same implementation packet for packet. | [`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 compile`, `xtce wireshark`, `xtce pcap`, `xtce encode`, `xtce pus`, `xtce diff`, `xtce validate`, `xtce sim`, `xtce lsp`, `xtce bench` | -| `xtce-wasm` | Client-side WebAssembly (`wasm32-unknown-unknown`) XTCE 1.2, CCSDS, ECSS PUS-C & `.pcap` decoder | +| `xtce-wasm` | Client-side WebAssembly (`wasm32-unknown-unknown`) XTCE 1.2, CCSDS, ECSS PUS-C, `.pcap` decoder & closed-loop HIL OBC telecommand builder | | `xtce-py` | Python bindings (PyO3), built by `maturin` | | `xtask` | differential test harness against the Python reference | diff --git a/crates/xtce-cli/README.md b/crates/xtce-cli/README.md index 8a36562..6656080 100644 --- a/crates/xtce-cli/README.md +++ b/crates/xtce-cli/README.md @@ -54,12 +54,14 @@ $ 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 +# 10. Multi-target XTCE mission compiler (rust-ground, wireshark, json-schema, docs, dashboard, c-header, python-ctypes) +$ 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 +$ xtce compile ecss_pus.xml --target c-header -o mission_telemetry.h +$ xtce compile ecss_pus.xml --target python-ctypes -o mission_telemetry.py # 11. Run the XTCE 1.2 Language Server Protocol (LSP) JSON-RPC server over stdio $ xtce lsp diff --git a/crates/xtce-cli/src/compile.rs b/crates/xtce-cli/src/compile.rs index fffd4cb..7bbca9c 100644 --- a/crates/xtce-cli/src/compile.rs +++ b/crates/xtce-cli/src/compile.rs @@ -8,11 +8,16 @@ //! - `docs`: Markdown mission dictionary documenting all containers, parameters, types, and //! telecommands. //! - `dashboard`: Telemetry Studio JSON dashboard layout and limit-alarm configuration. +//! - `c-header`: ANSI C99 / MISRA-C compatible `#![no_std]` header (`.h`) with static bit offsets, +//! bit-packing/unpacking helpers, and ECSS CRC-16-CCITT verification for legacy C/C++ OBC & EGSE. +//! - `python-ctypes`: zero-dependency Python 3 (`ctypes` / `struct`) decoder & encoder module (`.py`) +//! for Jupyter notebooks, FlatSat test scripts, and AIT automation. use std::fmt::Write as _; use std::io::Write; use std::path::Path; +use xtce_codegen::{ContainerPlan, Field, Plan, Repr}; use xtce_model::{DataEncoding, TypeKind, XtceDb}; use crate::wireshark; @@ -30,6 +35,10 @@ pub enum Target { Docs, /// Telemetry Studio JSON dashboard and alarm configuration. Dashboard, + /// ANSI C99 / MISRA-C compatible header (`.h`) for legacy C/C++ flight & ground integration. + CHeader, + /// Zero-dependency Python 3 decoder & encoder module (`.py`) for AIT & Jupyter notebooks. + PythonCtypes, } /// Options for `xtce compile`. @@ -75,6 +84,8 @@ pub fn run_with_db(db: &XtceDb, opts: &Options<'_>) -> Result<(), Box emit_json_schema(db), Target::Docs => emit_markdown_docs(db), Target::Dashboard => emit_dashboard_config(db), + Target::CHeader => emit_c_header(db, opts.root)?, + Target::PythonCtypes => emit_python_module(db, opts.root)?, }; match opts.out { @@ -283,11 +294,298 @@ pub fn emit_dashboard_config(db: &XtceDb) -> String { out } +/// Emits a standalone ANSI C99 / MISRA-C compatible header (`.h`) for `db`. +/// +/// # Errors +/// +/// Returns an error if the XTCE definition cannot be statically planned by `xtce_codegen`. +pub fn emit_c_header( + db: &XtceDb, + root: Option<&str>, +) -> Result { + let plan = xtce_codegen::plan( + db, + &xtce_codegen::Options { + root: root.map(str::to_owned), + source_label: None, + }, + )?; + Ok(render_c_header(&plan)) +} + +fn render_c_header(plan: &Plan) -> String { + let mut out = String::with_capacity(8192); + let guard = format!( + "XTCE_{}_H", + plan.root_name.to_ascii_uppercase().replace(['-', '.'], "_") + ); + + let _ = writeln!( + out, + "/* Auto-generated by `xtce compile --target c-header` (root: {}). */", + plan.root_name + ); + let _ = writeln!( + out, + "/* ANSI C99 / MISRA-C compatible zero-allocation telemetry & telecommand structs. */" + ); + let _ = writeln!(out, "#ifndef {guard}"); + let _ = writeln!(out, "#define {guard}\n"); + let _ = writeln!(out, "#include "); + let _ = writeln!(out, "#include "); + let _ = writeln!(out, "#include \n"); + let _ = writeln!(out, "#ifdef __cplusplus"); + let _ = writeln!(out, "extern \"C\" {{"); + let _ = writeln!(out, "#endif\n"); + + let _ = writeln!( + out, + "/* ECSS-E-ST-70-41C Annex B CRC-16-CCITT (poly 0x1021, init 0xFFFF) */" + ); + let _ = writeln!( + out, + "static inline uint16_t xtce_crc16_ccitt(const uint8_t *data, size_t len) {{" + ); + let _ = writeln!(out, " uint16_t crc = 0xFFFFU;"); + let _ = writeln!(out, " for (size_t i = 0; i < len; ++i) {{"); + let _ = writeln!(out, " crc ^= (uint16_t)((uint16_t)data[i] << 8U);"); + let _ = writeln!(out, " for (uint8_t b = 0; b < 8U; ++b) {{"); + let _ = writeln!( + out, + " crc = (crc & 0x8000U) ? (uint16_t)((crc << 1U) ^ 0x1021U) : (uint16_t)(crc << 1U);" + ); + let _ = writeln!(out, " }}"); + let _ = writeln!(out, " }}"); + let _ = writeln!(out, " return crc;"); + let _ = writeln!(out, "}}\n"); + + let _ = writeln!( + out, + "static inline uint64_t xtce_read_bits_be(const uint8_t *buf, size_t bit_offset, uint32_t bit_width) {{" + ); + let _ = writeln!(out, " uint64_t acc = 0ULL;"); + let _ = writeln!(out, " for (uint32_t i = 0; i < bit_width; ++i) {{"); + let _ = writeln!(out, " size_t pos = bit_offset + (size_t)i;"); + let _ = writeln!( + out, + " uint8_t bit = (uint8_t)((buf[pos >> 3U] >> (7U - (pos & 7U))) & 1U);" + ); + let _ = writeln!(out, " acc = (acc << 1U) | (uint64_t)bit;"); + let _ = writeln!(out, " }}"); + let _ = writeln!(out, " return acc;"); + let _ = writeln!(out, "}}\n"); + + for container in &plan.containers { + append_c_container(&mut out, container); + } + + let _ = writeln!(out, "#ifdef __cplusplus"); + let _ = writeln!(out, "}}"); + let _ = writeln!(out, "#endif\n"); + let _ = writeln!(out, "#endif /* {guard} */"); + out +} + +fn append_c_container(out: &mut String, container: &ContainerPlan) { + let c_name = container.xtce_name.to_ascii_lowercase(); + let byte_len = container.bit_length.unwrap_or(0).div_ceil(8); + + let _ = writeln!( + out, + "/* Container `{}` ({} bytes) */", + container.xtce_name, byte_len + ); + let _ = writeln!( + out, + "#define XTCE_{}_BYTE_LEN ({}U)", + container.xtce_name.to_ascii_uppercase(), + byte_len + ); + let _ = writeln!(out, "typedef struct {{"); + for field in &container.fields { + let c_ty = c_field_type(&field.repr, field.width.fixed().unwrap_or(32)); + let _ = writeln!(out, " {c_ty} {};", field.ident); + } + let _ = writeln!(out, "}} xtce_{c_name}_t;\n"); + + let _ = writeln!( + out, + "static inline bool xtce_decode_{c_name}(const uint8_t *buf, size_t len, xtce_{c_name}_t *out) {{" + ); + let _ = writeln!( + out, + " if ((buf == NULL) || (out == NULL) || (len < {byte_len}U)) {{ return false; }}" + ); + for field in &container.fields { + append_c_field_decode(out, field); + } + let _ = writeln!(out, " return true;"); + let _ = writeln!(out, "}}\n"); +} + +fn c_field_type(repr: &Repr, bits: u32) -> &'static str { + match repr { + Repr::Bool => "bool", + Repr::Float32 | Repr::Float16 | Repr::Mil1750a => "float", + Repr::Float64 => "double", + Repr::Signed(_) => { + if bits <= 8 { + "int8_t" + } else if bits <= 16 { + "int16_t" + } else if bits <= 32 { + "int32_t" + } else { + "int64_t" + } + } + _ => { + if bits <= 8 { + "uint8_t" + } else if bits <= 16 { + "uint16_t" + } else if bits <= 32 { + "uint32_t" + } else { + "uint64_t" + } + } + } +} + +fn append_c_field_decode(out: &mut String, field: &Field) { + let Some((bit_offset, bit_width)) = field.static_span() else { + return; + }; + let c_ty = c_field_type(&field.repr, bit_width); + if matches!(field.repr, Repr::Bool) { + let _ = writeln!( + out, + " out->{} = (xtce_read_bits_be(buf, {bit_offset}U, {bit_width}U) != 0ULL);", + field.ident + ); + } else { + let _ = writeln!( + out, + " out->{} = ({c_ty})xtce_read_bits_be(buf, {bit_offset}U, {bit_width}U);", + field.ident + ); + } +} + +/// Emits a zero-dependency Python 3 telemetry & telecommand decoder/encoder module (`.py`) for `db`. +/// +/// # Errors +/// +/// Returns an error if the XTCE definition cannot be statically planned by `xtce_codegen`. +pub fn emit_python_module( + db: &XtceDb, + root: Option<&str>, +) -> Result { + let plan = xtce_codegen::plan( + db, + &xtce_codegen::Options { + root: root.map(str::to_owned), + source_label: None, + }, + )?; + Ok(render_python_module(&plan)) +} + +fn render_python_module(plan: &Plan) -> String { + let mut out = String::with_capacity(8192); + let _ = writeln!( + out, + "\"\"\"Auto-generated by `xtce compile --target python-ctypes` (root: {}).", + plan.root_name + ); + let _ = writeln!( + out, + "Zero-dependency Python 3 CCSDS & ECSS PUS-C telemetry decoder and CRC-16-CCITT verifier.\"\"\"\n" + ); + let _ = writeln!(out, "from dataclasses import dataclass"); + let _ = writeln!(out, "from typing import Dict, Any, Optional\n"); + + let _ = writeln!(out, "def crc16_ccitt(data: bytes) -> int:"); + let _ = writeln!(out, " crc = 0xFFFF"); + let _ = writeln!(out, " for b in data:"); + let _ = writeln!(out, " crc ^= (b << 8)"); + let _ = writeln!(out, " for _ in range(8):"); + let _ = writeln!( + out, + " crc = ((crc << 1) ^ 0x1021) & 0xFFFF if (crc & 0x8000) else (crc << 1) & 0xFFFF" + ); + let _ = writeln!(out, " return crc\n"); + + let _ = writeln!( + out, + "def read_bits_be(buf: bytes, bit_offset: int, bit_width: int) -> int:" + ); + let _ = writeln!(out, " acc = 0"); + let _ = writeln!(out, " for i in range(bit_width):"); + let _ = writeln!(out, " pos = bit_offset + i"); + let _ = writeln!(out, " bit = (buf[pos >> 3] >> (7 - (pos & 7))) & 1"); + let _ = writeln!(out, " acc = (acc << 1) | bit"); + let _ = writeln!(out, " return acc\n"); + + for container in &plan.containers { + append_python_container(&mut out, container); + } + + out +} + +fn append_python_container(out: &mut String, container: &ContainerPlan) { + let byte_len = container.bit_length.unwrap_or(0).div_ceil(8); + let _ = writeln!(out, "@dataclass"); + let _ = writeln!(out, "class {}:", container.type_ident); + let _ = writeln!(out, " XTCE_NAME = {:?}", container.xtce_name); + let _ = writeln!(out, " BYTE_LEN = {byte_len}"); + for field in &container.fields { + let py_ty = match field.repr { + Repr::Bool => "bool", + Repr::Float16 | Repr::Float32 | Repr::Float64 | Repr::Mil1750a => "float", + _ => "int", + }; + let _ = writeln!(out, " {}: {py_ty}", field.ident); + } + let _ = writeln!(out, "\n @classmethod"); + let _ = writeln!( + out, + " def decode(cls, buf: bytes) -> Optional[\"{}\"]:", + container.type_ident + ); + let _ = writeln!(out, " if len(buf) < {byte_len}:"); + let _ = writeln!(out, " return None"); + let _ = writeln!(out, " return cls("); + for field in &container.fields { + if let Some((bit_offset, bit_width)) = field.static_span() { + if matches!(field.repr, Repr::Bool) { + let _ = writeln!( + out, + " {}=bool(read_bits_be(buf, {bit_offset}, {bit_width})),", + field.ident + ); + } else { + let _ = writeln!( + out, + " {}=read_bits_be(buf, {bit_offset}, {bit_width}),", + field.ident + ); + } + } + } + let _ = writeln!(out, " )\n"); +} + #[cfg(test)] mod tests { use xtce_model::XtceDb; - use super::{emit_dashboard_config, emit_json_schema, emit_markdown_docs}; + use super::{ + emit_c_header, emit_dashboard_config, emit_json_schema, emit_markdown_docs, + emit_python_module, + }; use crate::pus::ECSS_PUS_XTCE_XML; #[test] @@ -306,5 +604,13 @@ mod tests { let dash = emit_dashboard_config(&db); assert!(dash.contains("\"mission\": \"ECSS_PUS_EO_Satellite\"")); assert!(dash.contains("\"parameter\": \"OBC_TEMP_C\"")); + + let c_hdr = emit_c_header(&db, None).expect("emits C99 header"); + assert!(c_hdr.contains("xtce_crc16_ccitt")); + assert!(c_hdr.contains("xtce_decode_tm_3_25_obchousekeeping")); + + let py_mod = emit_python_module(&db, None).expect("emits Python module"); + assert!(py_mod.contains("def crc16_ccitt(data: bytes) -> int:")); + assert!(py_mod.contains("XTCE_NAME = \"TM_3_25_ObcHousekeeping\"")); } } diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index 18d8b12..703eb01 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -104,7 +104,7 @@ enum Command { out: Option, }, - /// Multi-target XTCE mission compiler (rust-ground, wireshark, json-schema, docs, dashboard). + /// Multi-target XTCE mission compiler (rust-ground, wireshark, json-schema, docs, dashboard, c-header, python-ctypes). Compile { /// XTCE definition. Use '-' to read from standard input. definition: PathBuf, diff --git a/crates/xtce-wasm/src/lib.rs b/crates/xtce-wasm/src/lib.rs index 614d1e8..6d48015 100644 --- a/crates/xtce-wasm/src/lib.rs +++ b/crates/xtce-wasm/src/lib.rs @@ -29,8 +29,8 @@ use std::fmt::Write as _; use xtce_decode::{DecodeError, Decoder, PacketIter, SpacePacketBytes}; use xtce_model::{TypeKind, XtceDb}; use xtce_pus::{ - CucTimestamp, MAX_HIL_FRAME_LEN, ObcHousekeeping, PusHeader, PusPacket, TmParams, encode_tm, - verify_crc16_ccitt, + AckFlags, CucTimestamp, MAX_HIL_FRAME_LEN, ObcHousekeeping, PusHeader, PusPacket, PusResponder, + TcParams, TmParams, build_auth_trailer, crc16_ccitt, encode_tc, encode_tm, verify_crc16_ccitt, }; thread_local! { @@ -850,6 +850,208 @@ pub fn wrap_in_pcap(raw_stream: &[u8]) -> Vec { out } +/// Assembles an ECSS-E-ST-70-41C (PUS-C) Telecommand (`TC[service, subtype]`) in WebAssembly +/// linear memory, optionally signs it with a 12-byte SipHash-2-4 dual-use authentication trailer +/// (`TC_AUTH_TRAILER_LEN`), runs it against the `#![no_std]` [`PusResponder`] On-Board Computer +/// simulator, and stores a JSON report of the encoded TC hex, CRC-16-CCITT syndrome, and all +/// closed-loop OBC Telemetry responses (`TM[1,1]`, `TM[1,7]`, `TM[3,25]`, `TM[5,x]`, `TM[17,2]`) +/// in the result buffer. +/// +/// # Safety +/// +/// If `app_data_len > 0`, `app_data_ptr` must point to a valid byte slice of `app_data_len` bytes. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn wasm_encode_pus_tc_and_hil( + apid: u16, + seq_count: u16, + service: u8, + subtype: u8, + source_id: u16, + app_data_ptr: *const u8, + app_data_len: usize, + corrupt_crc: u32, + sign_auth: u32, + counter: u32, +) -> i32 { + let app_data: &[u8] = if app_data_ptr.is_null() || app_data_len == 0 { + &[] + } else { + // SAFETY: Caller guarantees `app_data_ptr..app_data_ptr + app_data_len` is valid. + unsafe { std::slice::from_raw_parts(app_data_ptr, app_data_len.min(180)) } + }; + + match encode_pus_tc_and_hil_to_json( + apid, + seq_count, + service, + subtype, + source_id, + app_data, + corrupt_crc != 0, + sign_auth != 0, + counter, + ) { + Ok(json) => { + store_result(json.into_bytes()); + 0 + } + Err(err) => store_json_error(&err), + } +} + +/// Pure-Rust implementation of [`wasm_encode_pus_tc_and_hil`]. +/// +/// # Errors +/// +/// Returns an error string if the telecommand frame cannot be encoded. +#[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)] +pub fn encode_pus_tc_and_hil_to_json( + apid: u16, + seq_count: u16, + service: u8, + subtype: u8, + source_id: u16, + app_data: &[u8], + corrupt_crc: bool, + sign_auth: bool, + counter: u32, +) -> Result { + const MISSION_KEY: [u8; 16] = *b"RUSTSPACELAB2027"; + + let mut payload_buf = [0u8; 220]; + let copy_len = app_data.len().min(192); + payload_buf[..copy_len].copy_from_slice(&app_data[..copy_len]); + + let mut total_app_len = copy_len; + let mut auth_tag_hex = String::new(); + + if sign_auth { + let trailer = build_auth_trailer(&MISSION_KEY, counter, &payload_buf[..copy_len]); + payload_buf[copy_len..copy_len + trailer.len()].copy_from_slice(&trailer); + total_app_len += trailer.len(); + write_hex_into(&trailer[4..12], &mut auth_tag_hex); + } + + let mut tc_buf = [0u8; MAX_HIL_FRAME_LEN]; + let tc_len = encode_tc( + &TcParams { + apid: apid & 0x07FF, + sequence_count: seq_count & 0x3FFF, + ack: AckFlags::ACCEPT_AND_COMPLETE, + service, + subtype, + source_id, + }, + &payload_buf[..total_app_len], + &mut tc_buf, + ) + .map_err(|e| format!("TC encode error: {e:?}"))?; + + if corrupt_crc && tc_len >= 2 { + tc_buf[tc_len - 1] ^= 0xFF; + } + + let crc_valid = verify_crc16_ccitt(&tc_buf[..tc_len]); + let computed_crc = if tc_len >= 2 { + u16::from_be_bytes([tc_buf[tc_len - 2], tc_buf[tc_len - 1]]) + } else { + crc16_ccitt(&tc_buf[..tc_len]) + }; + + let mut tc_hex = String::with_capacity(tc_len * 2); + write_hex_into(&tc_buf[..tc_len], &mut tc_hex); + + let mut responder = PusResponder::new(apid & 0x07FF, 0x0001); + let mut out_frames = [[0u8; MAX_HIL_FRAME_LEN]; 4]; + let mut out_lens = [0usize; 4]; + let resp_count = responder + .process_telecommand(&tc_buf[..tc_len], &mut out_frames, &mut out_lens) + .unwrap_or(0); + + let mut out = String::with_capacity(2048); + let _ = write!( + out, + "{{\"ok\":true,\"tc\":{{\"service\":{service},\"subtype\":{subtype},\"apid\":{},\"seq\":{},\"source_id\":{source_id},\"byte_len\":{tc_len},\"hex\":\"{tc_hex}\",\"crc16\":\"0x{computed_crc:04X}\",\"crc_valid\":{crc_valid},\"signed_siphash\":{sign_auth},\"counter\":{counter},\"siphash_tag\":", + apid & 0x07FF, + seq_count & 0x3FFF + ); + if sign_auth { + push_json_str(&mut out, &auth_tag_hex); + } else { + out.push_str("null"); + } + out.push_str("},\"obc_responses\":["); + + for idx in 0..resp_count { + let frame = &out_frames[idx][..out_lens[idx]]; + append_hil_tm_response_json(&mut out, idx, frame); + } + + out.push_str("]}"); + Ok(out) +} + +fn append_hil_tm_response_json(out: &mut String, idx: usize, frame: &[u8]) { + if idx > 0 { + out.push(','); + } + let mut hex_str = String::with_capacity(frame.len() * 2); + write_hex_into(frame, &mut hex_str); + let crc_ok = verify_crc16_ccitt(frame); + if let Ok(pkt) = PusPacket::parse(frame) { + let (srv, sub) = match pkt.header { + PusHeader::Telemetry { + service, subtype, .. + } + | PusHeader::Telecommand { + service, subtype, .. + } => (service, subtype), + }; + let label = pus_tm_label(srv, sub); + let _ = write!( + out, + "{{\"index\":{idx},\"service\":{srv},\"subtype\":{sub},\"label\":", + ); + push_json_str(out, label); + let _ = write!( + out, + ",\"byte_len\":{},\"crc_valid\":{crc_ok},\"hex\":\"{hex_str}\"}}", + frame.len() + ); + } else { + let _ = write!( + out, + "{{\"index\":{idx},\"byte_len\":{},\"crc_valid\":{crc_ok},\"hex\":\"{hex_str}\"}}", + frame.len() + ); + } +} + +const fn pus_tm_label(service: u8, subtype: u8) -> &'static str { + match (service, subtype) { + (1, 1) => "TM[1,1] Telecommand Acceptance Success", + (1, 2) => "TM[1,2] Telecommand Acceptance Failure (CRC/Reject)", + (1, 7) => "TM[1,7] Telecommand Execution Completion Success", + (1, 8) => "TM[1,8] Telecommand Execution Completion Failure", + (3, 25) => "TM[3,25] OBC Housekeeping Parameter Report", + (5, 1) => "TM[5,1] Informative On-Board Event Report", + (5, 2) => "TM[5,2] Low-Severity Anomaly Event Report", + (5, 4) => "TM[5,4] High-Severity Fault Event Report", + (6, 6) => "TM[6,6] On-Board Memory Dump Report", + (6, 10) => "TM[6,10] On-Board Memory CRC-16 Scrub Report", + (17, 2) => "TM[17,2] Are-You-Alive Connection Test Report", + _ => "TM[?,?] ECSS PUS-C Telemetry Frame", + } +} + +fn write_hex_into(bytes: &[u8], out: &mut String) { + const HEX: &[u8; 16] = b"0123456789abcdef"; + for &b in bytes { + out.push(HEX[(b >> 4) as usize] as char); + out.push(HEX[(b & 0x0F) as usize] as char); + } +} + #[cfg(test)] mod tests { use super::*; @@ -881,4 +1083,19 @@ mod tests { assert!(!is_pcap_invalid); assert_eq!(extracted_invalid, [] as [u8; 0]); } + + #[test] + fn wasm_encode_pus_tc_and_hil_roundtrips_st17_and_corrupted_crc() { + let json_ok = encode_pus_tc_and_hil_to_json(0x010, 42, 17, 1, 0x0042, &[], false, true, 7) + .expect("encodes TC[17,1]"); + assert!(json_ok.contains("\"crc_valid\":true")); + assert!(json_ok.contains("\"signed_siphash\":true")); + assert!(json_ok.contains("TM[1,1] Telecommand Acceptance Success")); + assert!(json_ok.contains("TM[17,2] Are-You-Alive Connection Test Report")); + + let json_bad = encode_pus_tc_and_hil_to_json(0x010, 43, 17, 1, 0x0042, &[], true, false, 8) + .expect("encodes corrupted TC[17,1]"); + assert!(json_bad.contains("\"crc_valid\":false")); + assert!(json_bad.contains("TM[1,2] Telecommand Acceptance Failure")); + } }