Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down
14 changes: 8 additions & 6 deletions crates/xtce-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
308 changes: 307 additions & 1 deletion crates/xtce-cli/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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`.
Expand Down Expand Up @@ -75,6 +84,8 @@ pub fn run_with_db(db: &XtceDb, opts: &Options<'_>) -> Result<(), Box<dyn std::e
Target::JsonSchema => 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 {
Expand Down Expand Up @@ -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<String, xtce_codegen::CodegenError> {
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 <stdint.h>");
let _ = writeln!(out, "#include <stddef.h>");
let _ = writeln!(out, "#include <stdbool.h>\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<String, xtce_codegen::CodegenError> {
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]
Expand All @@ -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\""));
}
}
2 changes: 1 addition & 1 deletion crates/xtce-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ enum Command {
out: Option<PathBuf>,
},

/// 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,
Expand Down
Loading
Loading