Compare commits
46 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f001234025 | |||
|
|
e5a7839901
|
||
| 5707c6322a | |||
|
|
093f82ae86
|
||
| e68d1ade48 | |||
|
|
fbdc325d0d | ||
| 4bc0219cb2 | |||
| 3f4f76849f | |||
| fb1e2fc583 | |||
|
|
96e5851864
|
||
| b4d00c26c5 | |||
|
|
a8b64f2fef
|
||
| e7cb6f2a7a | |||
|
|
973ba4d3c4
|
||
| 8789e34c14 | |||
|
|
a68e82a825
|
||
| 0b46fa785b | |||
|
|
c57ee3e131
|
||
| 6ac84c3dca | |||
|
|
374f39f13b
|
||
| 2bc6167710 | |||
|
|
cfe0937afe
|
||
| e1c693cb29 | |||
|
|
38165420b7 | ||
| 0d09ff7825 | |||
|
|
8f2096ca35
|
||
| 3f35e9dba9 | |||
|
|
ea96099f55 | ||
| e117239852 | |||
|
|
844c517a94 | ||
| 0ae2ac149b | |||
|
|
2b41f9754d
|
||
| 8e2e0ce632 | |||
|
|
14d935ac2a | ||
| 756a803213 | |||
|
|
937bdeaf54
|
||
| bc30143d61 | |||
|
|
549e323211 | ||
| 82c3e06ac0 | |||
|
|
750add26ef | ||
| c3ff947fb0 | |||
|
|
8d86ecc8ee | ||
| 4b2bebb8cb | |||
|
|
e0b7a6a6bb
|
||
| 49983a5d6c | |||
|
|
04c864d6a2
|
3
.github/workflows/ci.yml
vendored
3
.github/workflows/ci.yml
vendored
@@ -39,12 +39,13 @@ jobs:
|
||||
matrix:
|
||||
target:
|
||||
- armv7-unknown-linux-gnueabihf
|
||||
- thumbv6m-none-eabi
|
||||
- thumbv7em-none-eabihf
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: "armv7-unknown-linux-gnueabihf, thumbv7em-none-eabihf"
|
||||
targets: "armv7-unknown-linux-gnueabihf, thumbv7em-none-eabihf, thumbv6m-none-eabi"
|
||||
- run: cargo check --release --target=${{matrix.target}} --no-default-features
|
||||
|
||||
fmt:
|
||||
|
||||
31
CHANGELOG.md
31
CHANGELOG.md
@@ -8,6 +8,34 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
# [unreleased]
|
||||
|
||||
# [v0.17.0] 2025-11-06
|
||||
|
||||
## Changed
|
||||
|
||||
- `CdsCommon` renamed to `CdsBase`
|
||||
- cfdp: Removed `FileDirectiveType` variant `*Pdu` suffix
|
||||
- ecss: Renamed `Subservice` to `MessageSubtypeId`
|
||||
- Simplified CDS short timestamp, contains one less field which reduced serialization length.
|
||||
- Renamed `UnsignedEnum::value` to `UnsignedEnum::value_raw`, `value` is reserved for the `const`
|
||||
value getter.
|
||||
- Renamed `CcsdsPrimaryHeader::from_composite_fields` to
|
||||
`CcsdsPrimaryHeader::new_from_composite_fields`
|
||||
- Renamed `PusPacket::service` to `PusPacket::service_type_id` and `PusPacket::subservice` to
|
||||
`PusPacket::message_subtype_id`. Also added `PusPacket::message_type_id`. Performed the same
|
||||
change for the ECSS PUS C secondary header traits.
|
||||
|
||||
## Added
|
||||
|
||||
- Added `CcsdsPacketCreator`, `CcsdsPacketReader`, `CcsdsPacketCreatorWithReservedData` and
|
||||
`CcsdsPacketCreatorOwned` which simplify the process of creating full CCSDS space packets.
|
||||
- Added new optional `portable-atomic` because portable atomics might not work on every
|
||||
architecture in addition to requiring atomic CAS support enabled inside for the crate.
|
||||
|
||||
## Fixed
|
||||
|
||||
- All `core::sync::Atomic?` usages are feature gated properly to allow compilation on systems
|
||||
without atomic CAS.
|
||||
|
||||
# [v0.16.1] 2025-09-26
|
||||
|
||||
## Fixed
|
||||
@@ -650,7 +678,8 @@ The timestamp of `PusTm` is now optional. See Added and Changed section for deta
|
||||
Initial release with CCSDS Space Packet Primary Header implementation and basic PUS TC and TM
|
||||
implementations.
|
||||
|
||||
[unreleased]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.16.1...HEAD
|
||||
[unreleased]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.17.0...HEAD
|
||||
[v0.17.0]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.16.1...v0.17.0
|
||||
[v0.16.1]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.16.0...v0.16.1
|
||||
[v0.16.0]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.15.0...v0.16.0
|
||||
[v0.15.0]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.14.0...v0.15.0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "spacepackets"
|
||||
version = "0.16.1"
|
||||
version = "0.17.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.83"
|
||||
authors = ["Robin Mueller <muellerr@irs.uni-stuttgart.de>"]
|
||||
@@ -14,15 +14,15 @@ categories = ["aerospace", "aerospace::space-protocols", "no-std", "hardware-sup
|
||||
|
||||
[dependencies]
|
||||
crc = "3"
|
||||
delegate = ">=0.8, <=0.13"
|
||||
delegate = "0.13"
|
||||
paste = "1"
|
||||
zerocopy = { version = "0.8", features = ["derive"] }
|
||||
thiserror = { version = "2", default-features = false }
|
||||
num_enum = { version = ">0.5, <=0.7", default-features = false }
|
||||
num_enum = { version = "0.7", default-features = false }
|
||||
num-traits = { version = "0.2", default-features = false }
|
||||
serde = { version = "1", optional = true, default-features = false, features = ["derive"] }
|
||||
arbitrary-int = { version = "2" }
|
||||
portable-atomic = "1"
|
||||
portable-atomic = { version = "1", optional = true }
|
||||
bitbybit = "1.4"
|
||||
|
||||
time = { version = "0.3", default-features = false, optional = true }
|
||||
@@ -32,6 +32,7 @@ defmt = { version = "1", default-features = false, optional = true }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = ["alloc", "chrono/std", "chrono/clock", "thiserror/std"]
|
||||
portable-atomic = ["dep:portable-atomic", "portable-atomic/require-cas"]
|
||||
defmt = ["dep:defmt", "arbitrary-int/defmt"]
|
||||
serde = ["dep:serde", "chrono?/serde", "arbitrary-int/serde"]
|
||||
alloc = ["chrono?/alloc", "defmt?/alloc", "serde?/alloc"]
|
||||
|
||||
@@ -43,6 +43,9 @@ Currently, this includes the following components:
|
||||
- [`timelib`](https://crates.io/crates/time): Add basic support for the `time` time library.
|
||||
- [`defmt`](https://defmt.ferrous-systems.com/): Add support for the `defmt` by adding the
|
||||
[`defmt::Format`](https://defmt.ferrous-systems.com/format) derive on many types.
|
||||
- [`portable-atomic`](https://github.com/taiki-e/portable-atomic): Basic support for `portable-atomic`
|
||||
crate in addition to the support for core atomic types. This support requires atomic CAS support
|
||||
enabled in the portable atomic crate.
|
||||
|
||||
# Examples
|
||||
|
||||
|
||||
12
justfile
12
justfile
@@ -1,9 +1,12 @@
|
||||
all: check build embedded test clippy fmt docs coverage
|
||||
all: check build embedded test clippy check-fmt docs coverage
|
||||
|
||||
clippy:
|
||||
cargo clippy -- -D warnings
|
||||
|
||||
fmt:
|
||||
cargo fmt --all
|
||||
|
||||
check-fmt:
|
||||
cargo fmt --all -- --check
|
||||
|
||||
check:
|
||||
@@ -11,6 +14,7 @@ check:
|
||||
|
||||
embedded:
|
||||
cargo build --target thumbv7em-none-eabihf --no-default-features
|
||||
cargo build --target thumbv6m-none-eabi --no-default-features
|
||||
|
||||
test:
|
||||
cargo nextest r --all-features
|
||||
@@ -20,12 +24,10 @@ build:
|
||||
cargo build --all-features
|
||||
|
||||
docs:
|
||||
export RUSTDOCFLAGS="--cfg docsrs --generate-link-to-definition -Z unstable-options"
|
||||
cargo +nightly doc --all-features
|
||||
RUSTDOCFLAGS="--cfg docsrs -Z unstable-options --generate-link-to-definition" cargo +nightly doc --all-features
|
||||
|
||||
docs-html:
|
||||
export RUSTDOCFLAGS="--cfg docsrs --generate-link-to-definition -Z unstable-options"
|
||||
cargo +nightly doc --all-features --open
|
||||
RUSTDOCFLAGS="--cfg docsrs -Z unstable-options --generate-link-to-definition" cargo +nightly doc --all-features --open
|
||||
|
||||
coverage:
|
||||
cargo llvm-cov nextest
|
||||
|
||||
@@ -8,6 +8,7 @@ use std::string::String;
|
||||
|
||||
use super::TlvLvDataTooLargeError;
|
||||
|
||||
/// Minmum length of a CFDP length-value structure in bytes.
|
||||
pub const MIN_LV_LEN: usize = 1;
|
||||
|
||||
/// Generic CFDP length-value (LV) abstraction as specified in CFDP 5.1.8.
|
||||
@@ -63,8 +64,10 @@ pub(crate) fn generic_len_check_deserialization(
|
||||
}
|
||||
|
||||
impl<'data> Lv<'data> {
|
||||
/// Minimum length of a LV structure in bytes.
|
||||
pub const MIN_LEN: usize = MIN_LV_LEN;
|
||||
|
||||
/// Generic constructor.
|
||||
#[inline]
|
||||
pub fn new(data: &[u8]) -> Result<Lv<'_>, TlvLvDataTooLargeError> {
|
||||
if data.len() > u8::MAX as usize {
|
||||
@@ -118,6 +121,7 @@ impl<'data> Lv<'data> {
|
||||
self.data.len() == 0
|
||||
}
|
||||
|
||||
/// Raw value part of the LV.
|
||||
#[inline]
|
||||
pub fn value(&self) -> &[u8] {
|
||||
self.data
|
||||
@@ -179,7 +183,7 @@ impl<'data> Lv<'data> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
mod tests {
|
||||
use alloc::string::ToString;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -13,43 +13,55 @@ pub const CFDP_VERSION_2_NAME: &str = "CCSDS 727.0-B-5";
|
||||
/// Currently, only this version is supported.
|
||||
pub const CFDP_VERSION_2: u8 = 0b001;
|
||||
|
||||
/// PDU type.
|
||||
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||
#[repr(u8)]
|
||||
pub enum PduType {
|
||||
/// File directive PDU.
|
||||
FileDirective = 0,
|
||||
/// File data PDU.
|
||||
FileData = 1,
|
||||
}
|
||||
|
||||
/// PDU direction.
|
||||
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||
#[repr(u8)]
|
||||
pub enum Direction {
|
||||
/// Going towards the file receiver.
|
||||
TowardsReceiver = 0,
|
||||
/// Going towards the file sender.
|
||||
TowardsSender = 1,
|
||||
}
|
||||
|
||||
/// PDU transmission mode.
|
||||
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||
#[repr(u8)]
|
||||
pub enum TransmissionMode {
|
||||
/// Acknowledged (class 1) transfer.
|
||||
Acknowledged = 0,
|
||||
/// Unacknowledged (class 2) transfer.
|
||||
Unacknowledged = 1,
|
||||
}
|
||||
|
||||
/// CRC flag.
|
||||
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||
#[repr(u8)]
|
||||
pub enum CrcFlag {
|
||||
/// No CRC for the packet.
|
||||
NoCrc = 0,
|
||||
/// Packet has CRC.
|
||||
WithCrc = 1,
|
||||
}
|
||||
|
||||
@@ -78,7 +90,9 @@ impl From<CrcFlag> for bool {
|
||||
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||
#[repr(u8)]
|
||||
pub enum SegmentMetadataFlag {
|
||||
/// Segment metadata not present.
|
||||
NotPresent = 0,
|
||||
/// Segment metadata present.
|
||||
Present = 1,
|
||||
}
|
||||
|
||||
@@ -89,22 +103,30 @@ pub enum SegmentMetadataFlag {
|
||||
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||
#[repr(u8)]
|
||||
pub enum SegmentationControl {
|
||||
/// No record boundary preservation.
|
||||
NoRecordBoundaryPreservation = 0,
|
||||
/// With record boundary preservation.
|
||||
WithRecordBoundaryPreservation = 1,
|
||||
}
|
||||
|
||||
/// Fault handler codes according to the CFDP standard.
|
||||
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[bitbybit::bitenum(u3, exhaustive = false)]
|
||||
#[repr(u8)]
|
||||
pub enum FaultHandlerCode {
|
||||
/// Notice of cancellation fault handler code.
|
||||
NoticeOfCancellation = 0b0001,
|
||||
/// Notice of suspension fault handler code.
|
||||
NoticeOfSuspension = 0b0010,
|
||||
/// Ignore error fault handler code.
|
||||
IgnoreError = 0b0011,
|
||||
/// Abandon transaction fault handler code.
|
||||
AbandonTransaction = 0b0100,
|
||||
}
|
||||
|
||||
/// CFDP condition codes.
|
||||
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -113,15 +135,25 @@ pub enum FaultHandlerCode {
|
||||
pub enum ConditionCode {
|
||||
/// This is not an error condition for which a faulty handler override can be specified
|
||||
NoError = 0b0000,
|
||||
/// Positive acknowledgement limit reached.
|
||||
PositiveAckLimitReached = 0b0001,
|
||||
/// Keep-alive limit reached.
|
||||
KeepAliveLimitReached = 0b0010,
|
||||
/// Invalid transmission mode.
|
||||
InvalidTransmissionMode = 0b0011,
|
||||
/// Filestore rejection.
|
||||
FilestoreRejection = 0b0100,
|
||||
/// File checksum error.
|
||||
FileChecksumFailure = 0b0101,
|
||||
/// File size error.
|
||||
FileSizeError = 0b0110,
|
||||
/// NAK limit reached.
|
||||
NakLimitReached = 0b0111,
|
||||
/// Inactivity detected.
|
||||
InactivityDetected = 0b1000,
|
||||
/// Check limit reached.
|
||||
CheckLimitReached = 0b1010,
|
||||
/// Unsupported checksum type.
|
||||
UnsupportedChecksumType = 0b1011,
|
||||
/// Not an actual fault condition for which fault handler overrides can be specified
|
||||
SuspendRequestReceived = 0b1110,
|
||||
@@ -129,6 +161,7 @@ pub enum ConditionCode {
|
||||
CancelRequestReceived = 0b1111,
|
||||
}
|
||||
|
||||
/// Large file flag.
|
||||
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -151,6 +184,7 @@ pub enum TransactionStatus {
|
||||
/// Transaction is not currently active and the CFDP implementation does not retain a
|
||||
/// transaction history.
|
||||
Undefined = 0b00,
|
||||
/// Transaction is currently active.
|
||||
Active = 0b01,
|
||||
/// Transaction was active in the past and was terminated.
|
||||
Terminated = 0b10,
|
||||
@@ -161,28 +195,28 @@ pub enum TransactionStatus {
|
||||
|
||||
/// Checksum types according to the
|
||||
/// [SANA Checksum Types registry](https://sanaregistry.org/r/checksum_identifiers/)
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum ChecksumType {
|
||||
/// Modular legacy checksum
|
||||
Modular = 0,
|
||||
/// CRC32 Proximity-1.
|
||||
Crc32Proximity1 = 1,
|
||||
/// CRC32C.
|
||||
Crc32C = 2,
|
||||
/// Polynomial: 0x4C11DB7. Preferred checksum for now.
|
||||
/// CRC32. Polynomial: 0x4C11DB7. Preferred checksum for now.
|
||||
Crc32 = 3,
|
||||
/// Null checksum (no checksum).
|
||||
#[default]
|
||||
NullChecksum = 15,
|
||||
}
|
||||
|
||||
impl Default for ChecksumType {
|
||||
fn default() -> Self {
|
||||
Self::NullChecksum
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw null checksum.
|
||||
pub const NULL_CHECKSUM_U32: [u8; 4] = [0; 4];
|
||||
|
||||
/// TLV or LV data larger than allowed [u8::MAX].
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -199,16 +233,21 @@ pub struct InvalidTlvTypeFieldError {
|
||||
expected: Option<u8>,
|
||||
}
|
||||
|
||||
/// Generic TLV/LV error.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum TlvLvError {
|
||||
/// Data too large error.
|
||||
#[error("{0}")]
|
||||
DataTooLarge(#[from] TlvLvDataTooLargeError),
|
||||
/// Byte conversion error.
|
||||
#[error("byte conversion error: {0}")]
|
||||
ByteConversion(#[from] ByteConversionError),
|
||||
/// Invalid TLV type field error.
|
||||
#[error("{0}")]
|
||||
InvalidTlvTypeField(#[from] InvalidTlvTypeFieldError),
|
||||
/// Invalid value length.
|
||||
#[error("invalid value length {0}")]
|
||||
InvalidValueLength(usize),
|
||||
/// Only applies to filestore requests and responses. Second name was missing where one is
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
//! # Acknowledgement (ACK) PDU packet implementation.
|
||||
use crate::{
|
||||
cfdp::{ConditionCode, CrcFlag, Direction, TransactionStatus},
|
||||
ByteConversionError,
|
||||
@@ -10,6 +11,7 @@ use super::{
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Invalid [FileDirectiveType] of the acknowledged PDU error.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("invalid directive code of acknowledged PDU")]
|
||||
pub struct InvalidAckedDirectiveCodeError(pub FileDirectiveType);
|
||||
@@ -28,15 +30,16 @@ pub struct AckPdu {
|
||||
}
|
||||
|
||||
impl AckPdu {
|
||||
/// Constructor.
|
||||
pub fn new(
|
||||
mut pdu_header: PduHeader,
|
||||
directive_code_of_acked_pdu: FileDirectiveType,
|
||||
condition_code: ConditionCode,
|
||||
transaction_status: TransactionStatus,
|
||||
) -> Result<Self, InvalidAckedDirectiveCodeError> {
|
||||
if directive_code_of_acked_pdu == FileDirectiveType::EofPdu {
|
||||
if directive_code_of_acked_pdu == FileDirectiveType::Eof {
|
||||
pdu_header.pdu_conf.direction = Direction::TowardsSender;
|
||||
} else if directive_code_of_acked_pdu == FileDirectiveType::FinishedPdu {
|
||||
} else if directive_code_of_acked_pdu == FileDirectiveType::Finished {
|
||||
pdu_header.pdu_conf.direction = Direction::TowardsReceiver;
|
||||
} else {
|
||||
return Err(InvalidAckedDirectiveCodeError(directive_code_of_acked_pdu));
|
||||
@@ -52,6 +55,9 @@ impl AckPdu {
|
||||
Ok(ack_pdu)
|
||||
}
|
||||
|
||||
/// Constructor for an ACK PDU acknowledging an EOF PDU.
|
||||
///
|
||||
/// Relevant for the file receiver.
|
||||
pub fn new_for_eof_pdu(
|
||||
pdu_header: PduHeader,
|
||||
condition_code: ConditionCode,
|
||||
@@ -60,13 +66,16 @@ impl AckPdu {
|
||||
// Unwrap okay here, [new] can only fail on invalid directive codes.
|
||||
Self::new(
|
||||
pdu_header,
|
||||
FileDirectiveType::EofPdu,
|
||||
FileDirectiveType::Eof,
|
||||
condition_code,
|
||||
transaction_status,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Constructor for an ACK PDU acknowledging a Finished PDU.
|
||||
///
|
||||
/// Relevant for the file sender.
|
||||
pub fn new_for_finished_pdu(
|
||||
pdu_header: PduHeader,
|
||||
condition_code: ConditionCode,
|
||||
@@ -75,28 +84,32 @@ impl AckPdu {
|
||||
// Unwrap okay here, [new] can only fail on invalid directive codes.
|
||||
Self::new(
|
||||
pdu_header,
|
||||
FileDirectiveType::FinishedPdu,
|
||||
FileDirectiveType::Finished,
|
||||
condition_code,
|
||||
transaction_status,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// PDU header.
|
||||
#[inline]
|
||||
pub fn pdu_header(&self) -> &PduHeader {
|
||||
&self.pdu_header
|
||||
}
|
||||
|
||||
/// Directive code of the acknowledged PDU.
|
||||
#[inline]
|
||||
pub fn directive_code_of_acked_pdu(&self) -> FileDirectiveType {
|
||||
self.directive_code_of_acked_pdu
|
||||
}
|
||||
|
||||
/// Condition code.
|
||||
#[inline]
|
||||
pub fn condition_code(&self) -> ConditionCode {
|
||||
self.condition_code
|
||||
}
|
||||
|
||||
/// Transaction status.
|
||||
#[inline]
|
||||
pub fn transaction_status(&self) -> TransactionStatus {
|
||||
self.transaction_status
|
||||
@@ -110,6 +123,7 @@ impl AckPdu {
|
||||
3
|
||||
}
|
||||
|
||||
/// Construct [Self] from the provided byte slice.
|
||||
pub fn from_bytes(buf: &[u8]) -> Result<AckPdu, PduError> {
|
||||
let (pdu_header, mut current_idx) = PduHeader::from_bytes(buf)?;
|
||||
let full_len_without_crc = pdu_header.verify_length_and_checksum(buf)?;
|
||||
@@ -117,13 +131,13 @@ impl AckPdu {
|
||||
let directive_type = FileDirectiveType::try_from(buf[current_idx]).map_err(|_| {
|
||||
PduError::InvalidDirectiveType {
|
||||
found: buf[current_idx],
|
||||
expected: Some(FileDirectiveType::AckPdu),
|
||||
expected: Some(FileDirectiveType::Ack),
|
||||
}
|
||||
})?;
|
||||
if directive_type != FileDirectiveType::AckPdu {
|
||||
if directive_type != FileDirectiveType::Ack {
|
||||
return Err(PduError::WrongDirectiveType {
|
||||
found: directive_type,
|
||||
expected: FileDirectiveType::AckPdu,
|
||||
expected: FileDirectiveType::Ack,
|
||||
});
|
||||
}
|
||||
current_idx += 1;
|
||||
@@ -134,8 +148,8 @@ impl AckPdu {
|
||||
expected: None,
|
||||
}
|
||||
})?;
|
||||
if acked_directive_type != FileDirectiveType::EofPdu
|
||||
&& acked_directive_type != FileDirectiveType::FinishedPdu
|
||||
if acked_directive_type != FileDirectiveType::Eof
|
||||
&& acked_directive_type != FileDirectiveType::Finished
|
||||
{
|
||||
return Err(PduError::InvalidDirectiveType {
|
||||
found: acked_directive_type as u8,
|
||||
@@ -167,11 +181,11 @@ impl AckPdu {
|
||||
.into());
|
||||
}
|
||||
let mut current_idx = self.pdu_header.write_to_bytes(buf)?;
|
||||
buf[current_idx] = FileDirectiveType::AckPdu as u8;
|
||||
buf[current_idx] = FileDirectiveType::Ack as u8;
|
||||
current_idx += 1;
|
||||
|
||||
buf[current_idx] = (self.directive_code_of_acked_pdu as u8) << 4;
|
||||
if self.directive_code_of_acked_pdu == FileDirectiveType::FinishedPdu {
|
||||
if self.directive_code_of_acked_pdu == FileDirectiveType::Finished {
|
||||
// This is the directive subtype code. It needs to be set to 0b0001 if the ACK PDU
|
||||
// acknowledges a Finished PDU, and to 0b0000 otherwise.
|
||||
buf[current_idx] |= 0b0001;
|
||||
@@ -185,6 +199,7 @@ impl AckPdu {
|
||||
Ok(current_idx)
|
||||
}
|
||||
|
||||
/// Length of the written PDU in bytes.
|
||||
pub fn len_written(&self) -> usize {
|
||||
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||
}
|
||||
@@ -198,7 +213,7 @@ impl CfdpPdu for AckPdu {
|
||||
|
||||
#[inline]
|
||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||
Some(FileDirectiveType::AckPdu)
|
||||
Some(FileDirectiveType::Ack)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,10 +245,7 @@ mod tests {
|
||||
assert_eq!(ack_pdu.crc_flag(), expected_crc_flag);
|
||||
assert_eq!(ack_pdu.file_flag(), LargeFileFlag::Normal);
|
||||
assert_eq!(ack_pdu.pdu_type(), PduType::FileDirective);
|
||||
assert_eq!(
|
||||
ack_pdu.file_directive_type(),
|
||||
Some(FileDirectiveType::AckPdu)
|
||||
);
|
||||
assert_eq!(ack_pdu.file_directive_type(), Some(FileDirectiveType::Ack));
|
||||
assert_eq!(ack_pdu.transmission_mode(), TransmissionMode::Acknowledged);
|
||||
assert_eq!(ack_pdu.direction(), expected_dir);
|
||||
assert_eq!(ack_pdu.source_id(), TEST_SRC_ID.into());
|
||||
@@ -247,14 +259,14 @@ mod tests {
|
||||
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||
let ack_pdu = AckPdu::new(
|
||||
pdu_header,
|
||||
FileDirectiveType::FinishedPdu,
|
||||
FileDirectiveType::Finished,
|
||||
ConditionCode::NoError,
|
||||
TransactionStatus::Active,
|
||||
)
|
||||
.expect("creating ACK PDU failed");
|
||||
assert_eq!(
|
||||
ack_pdu.directive_code_of_acked_pdu(),
|
||||
FileDirectiveType::FinishedPdu
|
||||
FileDirectiveType::Finished
|
||||
);
|
||||
verify_state(&ack_pdu, CrcFlag::NoCrc, Direction::TowardsReceiver);
|
||||
}
|
||||
@@ -273,8 +285,8 @@ mod tests {
|
||||
assert_eq!(written, ack_pdu.len_written());
|
||||
verify_raw_header(ack_pdu.pdu_header(), &buf);
|
||||
|
||||
assert_eq!(buf[7], FileDirectiveType::AckPdu as u8);
|
||||
assert_eq!((buf[8] >> 4) & 0b1111, FileDirectiveType::FinishedPdu as u8);
|
||||
assert_eq!(buf[7], FileDirectiveType::Ack as u8);
|
||||
assert_eq!((buf[8] >> 4) & 0b1111, FileDirectiveType::Finished as u8);
|
||||
assert_eq!(buf[8] & 0b1111, 0b0001);
|
||||
assert_eq!(buf[9] >> 4 & 0b1111, condition_code as u8);
|
||||
assert_eq!(buf[9] & 0b11, transaction_status as u8);
|
||||
@@ -292,7 +304,7 @@ mod tests {
|
||||
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||
let ack_pdu = AckPdu::new(
|
||||
pdu_header,
|
||||
FileDirectiveType::FinishedPdu,
|
||||
FileDirectiveType::Finished,
|
||||
ConditionCode::NoError,
|
||||
TransactionStatus::Active,
|
||||
)
|
||||
@@ -320,12 +332,12 @@ mod tests {
|
||||
assert_eq!(
|
||||
AckPdu::new(
|
||||
pdu_header,
|
||||
FileDirectiveType::MetadataPdu,
|
||||
FileDirectiveType::Metadata,
|
||||
ConditionCode::NoError,
|
||||
TransactionStatus::Active,
|
||||
)
|
||||
.unwrap_err(),
|
||||
InvalidAckedDirectiveCodeError(FileDirectiveType::MetadataPdu)
|
||||
InvalidAckedDirectiveCodeError(FileDirectiveType::Metadata)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -372,7 +384,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(
|
||||
ack_pdu.directive_code_of_acked_pdu(),
|
||||
FileDirectiveType::EofPdu
|
||||
FileDirectiveType::Eof
|
||||
);
|
||||
verify_state(&ack_pdu, CrcFlag::WithCrc, Direction::TowardsSender);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
//! # End-of-File (EOF) PDU packet implementation.
|
||||
use crate::cfdp::pdu::{
|
||||
add_pdu_crc, generic_length_checks_pdu_deserialization, read_fss_field, write_fss_field,
|
||||
FileDirectiveType, PduError, PduHeader,
|
||||
@@ -25,6 +26,7 @@ pub struct EofPdu {
|
||||
}
|
||||
|
||||
impl EofPdu {
|
||||
/// Constructor.
|
||||
pub fn new(
|
||||
mut pdu_header: PduHeader,
|
||||
condition_code: ConditionCode,
|
||||
@@ -45,6 +47,7 @@ impl EofPdu {
|
||||
eof_pdu
|
||||
}
|
||||
|
||||
/// Constructor for no error EOF PDUs.
|
||||
pub fn new_no_error(pdu_header: PduHeader, file_checksum: u32, file_size: u64) -> Self {
|
||||
Self::new(
|
||||
pdu_header,
|
||||
@@ -55,21 +58,25 @@ impl EofPdu {
|
||||
)
|
||||
}
|
||||
|
||||
/// PDU header.
|
||||
#[inline]
|
||||
pub fn pdu_header(&self) -> &PduHeader {
|
||||
&self.pdu_header
|
||||
}
|
||||
|
||||
/// Condition code.
|
||||
#[inline]
|
||||
pub fn condition_code(&self) -> ConditionCode {
|
||||
self.condition_code
|
||||
}
|
||||
|
||||
/// File checksum.
|
||||
#[inline]
|
||||
pub fn file_checksum(&self) -> u32 {
|
||||
self.file_checksum
|
||||
}
|
||||
|
||||
/// File size.
|
||||
#[inline]
|
||||
pub fn file_size(&self) -> u64 {
|
||||
self.file_size
|
||||
@@ -90,6 +97,7 @@ impl EofPdu {
|
||||
len
|
||||
}
|
||||
|
||||
/// Construct [Self] from the provided byte slice.
|
||||
pub fn from_bytes(buf: &[u8]) -> Result<EofPdu, PduError> {
|
||||
let (pdu_header, mut current_idx) = PduHeader::from_bytes(buf)?;
|
||||
let full_len_without_crc = pdu_header.verify_length_and_checksum(buf)?;
|
||||
@@ -102,13 +110,13 @@ impl EofPdu {
|
||||
let directive_type = FileDirectiveType::try_from(buf[current_idx]).map_err(|_| {
|
||||
PduError::InvalidDirectiveType {
|
||||
found: buf[current_idx],
|
||||
expected: Some(FileDirectiveType::EofPdu),
|
||||
expected: Some(FileDirectiveType::Eof),
|
||||
}
|
||||
})?;
|
||||
if directive_type != FileDirectiveType::EofPdu {
|
||||
if directive_type != FileDirectiveType::Eof {
|
||||
return Err(PduError::WrongDirectiveType {
|
||||
found: directive_type,
|
||||
expected: FileDirectiveType::EofPdu,
|
||||
expected: FileDirectiveType::Eof,
|
||||
});
|
||||
}
|
||||
current_idx += 1;
|
||||
@@ -145,7 +153,7 @@ impl EofPdu {
|
||||
.into());
|
||||
}
|
||||
let mut current_idx = self.pdu_header.write_to_bytes(buf)?;
|
||||
buf[current_idx] = FileDirectiveType::EofPdu as u8;
|
||||
buf[current_idx] = FileDirectiveType::Eof as u8;
|
||||
current_idx += 1;
|
||||
buf[current_idx] = (self.condition_code as u8) << 4;
|
||||
current_idx += 1;
|
||||
@@ -165,6 +173,7 @@ impl EofPdu {
|
||||
Ok(current_idx)
|
||||
}
|
||||
|
||||
/// Length of the written PDU in bytes.
|
||||
pub fn len_written(&self) -> usize {
|
||||
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||
}
|
||||
@@ -178,7 +187,7 @@ impl CfdpPdu for EofPdu {
|
||||
|
||||
#[inline]
|
||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||
Some(FileDirectiveType::EofPdu)
|
||||
Some(FileDirectiveType::Eof)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,10 +230,7 @@ mod tests {
|
||||
assert_eq!(eof_pdu.crc_flag(), crc_flag);
|
||||
assert_eq!(eof_pdu.file_flag(), file_flag);
|
||||
assert_eq!(eof_pdu.pdu_type(), PduType::FileDirective);
|
||||
assert_eq!(
|
||||
eof_pdu.file_directive_type(),
|
||||
Some(FileDirectiveType::EofPdu)
|
||||
);
|
||||
assert_eq!(eof_pdu.file_directive_type(), Some(FileDirectiveType::Eof));
|
||||
assert_eq!(eof_pdu.transmission_mode(), TransmissionMode::Acknowledged);
|
||||
assert_eq!(eof_pdu.direction(), Direction::TowardsReceiver);
|
||||
assert_eq!(eof_pdu.source_id(), TEST_SRC_ID.into());
|
||||
@@ -253,7 +259,7 @@ mod tests {
|
||||
assert_eq!(written, eof_pdu.len_written());
|
||||
verify_raw_header(eof_pdu.pdu_header(), &buf);
|
||||
let mut current_idx = eof_pdu.pdu_header().header_len();
|
||||
buf[current_idx] = FileDirectiveType::EofPdu as u8;
|
||||
buf[current_idx] = FileDirectiveType::Eof as u8;
|
||||
current_idx += 1;
|
||||
assert_eq!(
|
||||
(buf[current_idx] >> 4) & 0b1111,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
//! # File Data PDU packet implementation
|
||||
use crate::cfdp::pdu::{
|
||||
add_pdu_crc, generic_length_checks_pdu_deserialization, read_fss_field, write_fss_field,
|
||||
PduError, PduHeader,
|
||||
@@ -10,18 +11,24 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{CfdpPdu, FileDirectiveType, WritablePduPacket};
|
||||
|
||||
/// Record continuation state for segment metadata.
|
||||
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[bitbybit::bitenum(u2, exhaustive = true)]
|
||||
#[repr(u8)]
|
||||
pub enum RecordContinuationState {
|
||||
/// No start and no end.
|
||||
NoStartNoEnd = 0b00,
|
||||
/// Start without end.
|
||||
StartWithoutEnd = 0b01,
|
||||
/// End without start.
|
||||
EndWithoutStart = 0b10,
|
||||
/// Start and end.
|
||||
StartAndEnd = 0b11,
|
||||
}
|
||||
|
||||
/// Segment metadata structure.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct SegmentMetadata<'seg_meta> {
|
||||
@@ -30,6 +37,7 @@ pub struct SegmentMetadata<'seg_meta> {
|
||||
}
|
||||
|
||||
impl<'seg_meta> SegmentMetadata<'seg_meta> {
|
||||
/// Constructor.
|
||||
pub fn new(
|
||||
record_continuation_state: RecordContinuationState,
|
||||
metadata: Option<&'seg_meta [u8]>,
|
||||
@@ -45,16 +53,19 @@ impl<'seg_meta> SegmentMetadata<'seg_meta> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Record continuation state.
|
||||
#[inline]
|
||||
pub fn record_continuation_state(&self) -> RecordContinuationState {
|
||||
self.record_continuation_state
|
||||
}
|
||||
|
||||
/// Raw metadata slice.
|
||||
#[inline]
|
||||
pub fn metadata(&self) -> Option<&'seg_meta [u8]> {
|
||||
self.metadata
|
||||
}
|
||||
|
||||
/// Length of the written segment metadata structure.
|
||||
#[inline]
|
||||
pub fn len_written(&self) -> usize {
|
||||
// Map empty metadata to 0 and slice to its length.
|
||||
@@ -169,24 +180,27 @@ pub struct FileDataPdu<'seg_meta, 'file_data> {
|
||||
}
|
||||
|
||||
impl<'seg_meta, 'file_data> FileDataPdu<'seg_meta, 'file_data> {
|
||||
/// Constructor for a file data PDU including segment metadata.
|
||||
pub fn new_with_seg_metadata(
|
||||
pdu_header: PduHeader,
|
||||
segment_metadata: SegmentMetadata<'seg_meta>,
|
||||
offset: u64,
|
||||
file_data: &'file_data [u8],
|
||||
) -> Self {
|
||||
Self::new_generic(pdu_header, Some(segment_metadata), offset, file_data)
|
||||
Self::new(pdu_header, Some(segment_metadata), offset, file_data)
|
||||
}
|
||||
|
||||
/// Constructor for a file data PDU without segment metadata.
|
||||
pub fn new_no_seg_metadata(
|
||||
pdu_header: PduHeader,
|
||||
offset: u64,
|
||||
file_data: &'file_data [u8],
|
||||
) -> Self {
|
||||
Self::new_generic(pdu_header, None, offset, file_data)
|
||||
Self::new(pdu_header, None, offset, file_data)
|
||||
}
|
||||
|
||||
pub fn new_generic(
|
||||
/// Generic constructor for a file data PDU.
|
||||
pub fn new(
|
||||
mut pdu_header: PduHeader,
|
||||
segment_metadata: Option<SegmentMetadata<'seg_meta>>,
|
||||
offset: u64,
|
||||
@@ -213,26 +227,31 @@ impl<'seg_meta, 'file_data> FileDataPdu<'seg_meta, 'file_data> {
|
||||
.calc_pdu_datafield_len(self.file_data.len() as u64)
|
||||
}
|
||||
|
||||
/// Optional segment metadata.
|
||||
#[inline]
|
||||
pub fn segment_metadata(&self) -> Option<&SegmentMetadata<'_>> {
|
||||
self.common.segment_metadata.as_ref()
|
||||
}
|
||||
|
||||
/// PDU header.
|
||||
#[inline]
|
||||
pub fn pdu_header(&self) -> &PduHeader {
|
||||
self.common.pdu_header()
|
||||
}
|
||||
|
||||
/// File data offset.
|
||||
#[inline]
|
||||
pub fn offset(&self) -> u64 {
|
||||
self.common.offset
|
||||
}
|
||||
|
||||
/// File data.
|
||||
#[inline]
|
||||
pub fn file_data(&self) -> &'file_data [u8] {
|
||||
self.file_data
|
||||
}
|
||||
|
||||
/// Read [Self] from the provided buffer.
|
||||
pub fn from_bytes<'buf: 'seg_meta + 'file_data>(buf: &'buf [u8]) -> Result<Self, PduError> {
|
||||
let (pdu_header, mut current_idx) = PduHeader::from_bytes(buf)?;
|
||||
let full_len_without_crc = pdu_header.verify_length_and_checksum(buf)?;
|
||||
@@ -281,6 +300,7 @@ impl<'seg_meta, 'file_data> FileDataPdu<'seg_meta, 'file_data> {
|
||||
Ok(current_idx)
|
||||
}
|
||||
|
||||
/// Length of the written PDU.
|
||||
pub fn len_written(&self) -> usize {
|
||||
self.common.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||
}
|
||||
@@ -323,20 +343,23 @@ pub struct FileDataPduCreatorWithReservedDatafield<'seg_meta> {
|
||||
}
|
||||
|
||||
impl<'seg_meta> FileDataPduCreatorWithReservedDatafield<'seg_meta> {
|
||||
/// Constructor for a file data PDU including segment metadata.
|
||||
pub fn new_with_seg_metadata(
|
||||
pdu_header: PduHeader,
|
||||
segment_metadata: SegmentMetadata<'seg_meta>,
|
||||
offset: u64,
|
||||
file_data_len: u64,
|
||||
) -> Self {
|
||||
Self::new_generic(pdu_header, Some(segment_metadata), offset, file_data_len)
|
||||
Self::new(pdu_header, Some(segment_metadata), offset, file_data_len)
|
||||
}
|
||||
|
||||
/// Constructor for a file data PDU without segment metadata.
|
||||
pub fn new_no_seg_metadata(pdu_header: PduHeader, offset: u64, file_data_len: u64) -> Self {
|
||||
Self::new_generic(pdu_header, None, offset, file_data_len)
|
||||
Self::new(pdu_header, None, offset, file_data_len)
|
||||
}
|
||||
|
||||
pub fn new_generic(
|
||||
/// Generic constructor.
|
||||
pub fn new(
|
||||
mut pdu_header: PduHeader,
|
||||
segment_metadata: Option<SegmentMetadata<'seg_meta>>,
|
||||
offset: u64,
|
||||
@@ -362,6 +385,7 @@ impl<'seg_meta> FileDataPduCreatorWithReservedDatafield<'seg_meta> {
|
||||
self.common.calc_pdu_datafield_len(self.file_data_len)
|
||||
}
|
||||
|
||||
/// Length of the written PDU.
|
||||
pub fn len_written(&self) -> usize {
|
||||
self.common.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||
}
|
||||
@@ -423,6 +447,7 @@ pub struct FileDataPduCreatorWithUnwrittenData<'buf> {
|
||||
}
|
||||
|
||||
impl FileDataPduCreatorWithUnwrittenData<'_> {
|
||||
/// Mutable access to the file data field.
|
||||
pub fn file_data_field_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.write_buf[self.file_data_offset as usize
|
||||
..self.file_data_offset as usize + self.file_data_len as usize]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
//! # Finished PDU packet implementation.
|
||||
use crate::cfdp::pdu::{
|
||||
add_pdu_crc, generic_length_checks_pdu_deserialization, FileDirectiveType, PduError, PduHeader,
|
||||
};
|
||||
@@ -13,23 +14,31 @@ use serde::{Deserialize, Serialize};
|
||||
use super::tlv::ReadableTlv;
|
||||
use super::{CfdpPdu, InvalidTlvTypeFieldError, WritablePduPacket};
|
||||
|
||||
/// Delivery code enumeration.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum DeliveryCode {
|
||||
/// Completed delivery.
|
||||
Complete = 0,
|
||||
/// Incomplete delivery.
|
||||
Incomplete = 1,
|
||||
}
|
||||
|
||||
/// File status enumeration.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum FileStatus {
|
||||
/// File was discarded deliberately.
|
||||
DiscardDeliberately = 0b00,
|
||||
/// File was rejected by the filestore.
|
||||
DiscardedFsRejection = 0b01,
|
||||
/// File was retained (but not necesarilly complete).
|
||||
Retained = 0b10,
|
||||
/// Unreported file status.
|
||||
Unreported = 0b11,
|
||||
}
|
||||
|
||||
@@ -65,6 +74,7 @@ impl<'fs_responses> FinishedPduCreator<'fs_responses> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructor where the fault location is provided.
|
||||
pub fn new_with_error(
|
||||
pdu_header: PduHeader,
|
||||
condition_code: ConditionCode,
|
||||
@@ -82,6 +92,7 @@ impl<'fs_responses> FinishedPduCreator<'fs_responses> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Generic constructor.
|
||||
pub fn new(
|
||||
mut pdu_header: PduHeader,
|
||||
condition_code: ConditionCode,
|
||||
@@ -109,32 +120,37 @@ impl<'fs_responses> FinishedPduCreator<'fs_responses> {
|
||||
finished_pdu
|
||||
}
|
||||
|
||||
/// PDU header.
|
||||
#[inline]
|
||||
pub fn pdu_header(&self) -> &PduHeader {
|
||||
&self.pdu_header
|
||||
}
|
||||
|
||||
/// Condition code.
|
||||
#[inline]
|
||||
pub fn condition_code(&self) -> ConditionCode {
|
||||
self.condition_code
|
||||
}
|
||||
|
||||
/// Delivery code.
|
||||
#[inline]
|
||||
pub fn delivery_code(&self) -> DeliveryCode {
|
||||
self.delivery_code
|
||||
}
|
||||
|
||||
/// File status.
|
||||
#[inline]
|
||||
pub fn file_status(&self) -> FileStatus {
|
||||
self.file_status
|
||||
}
|
||||
|
||||
// If there are no filestore responses, an empty slice will be returned.
|
||||
/// Filestore responses as a slice.
|
||||
#[inline]
|
||||
pub fn filestore_responses(&self) -> &[FilestoreResponseTlv<'_, '_, '_>] {
|
||||
self.fs_responses
|
||||
}
|
||||
|
||||
/// Optional fault location [EntityIdTlv].
|
||||
#[inline]
|
||||
pub fn fault_location(&self) -> Option<EntityIdTlv> {
|
||||
self.fault_location
|
||||
@@ -166,7 +182,7 @@ impl<'fs_responses> FinishedPduCreator<'fs_responses> {
|
||||
}
|
||||
|
||||
let mut current_idx = self.pdu_header.write_to_bytes(buf)?;
|
||||
buf[current_idx] = FileDirectiveType::FinishedPdu as u8;
|
||||
buf[current_idx] = FileDirectiveType::Finished as u8;
|
||||
current_idx += 1;
|
||||
buf[current_idx] = ((self.condition_code as u8) << 4)
|
||||
| ((self.delivery_code as u8) << 2)
|
||||
@@ -184,6 +200,7 @@ impl<'fs_responses> FinishedPduCreator<'fs_responses> {
|
||||
Ok(current_idx)
|
||||
}
|
||||
|
||||
/// Length of the written PDU in bytes.
|
||||
pub fn len_written(&self) -> usize {
|
||||
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||
}
|
||||
@@ -197,7 +214,7 @@ impl CfdpPdu for FinishedPduCreator<'_> {
|
||||
|
||||
#[inline]
|
||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||
Some(FileDirectiveType::FinishedPdu)
|
||||
Some(FileDirectiveType::Finished)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,6 +259,7 @@ impl<'buf> Iterator for FilestoreResponseIterator<'buf> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fnished PDU reader structure.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -269,13 +287,13 @@ impl<'buf> FinishedPduReader<'buf> {
|
||||
let directive_type = FileDirectiveType::try_from(buf[current_idx]).map_err(|_| {
|
||||
PduError::InvalidDirectiveType {
|
||||
found: buf[current_idx],
|
||||
expected: Some(FileDirectiveType::FinishedPdu),
|
||||
expected: Some(FileDirectiveType::Finished),
|
||||
}
|
||||
})?;
|
||||
if directive_type != FileDirectiveType::FinishedPdu {
|
||||
if directive_type != FileDirectiveType::Finished {
|
||||
return Err(PduError::WrongDirectiveType {
|
||||
found: directive_type,
|
||||
expected: FileDirectiveType::FinishedPdu,
|
||||
expected: FileDirectiveType::Finished,
|
||||
});
|
||||
}
|
||||
current_idx += 1;
|
||||
@@ -297,11 +315,13 @@ impl<'buf> FinishedPduReader<'buf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Raw filestore responses.
|
||||
#[inline]
|
||||
pub fn fs_responses_raw(&self) -> &[u8] {
|
||||
self.fs_responses_raw
|
||||
}
|
||||
|
||||
/// Iterator over the filestore responses.
|
||||
#[inline]
|
||||
pub fn fs_responses_iter(&self) -> FilestoreResponseIterator<'_> {
|
||||
FilestoreResponseIterator {
|
||||
@@ -310,26 +330,31 @@ impl<'buf> FinishedPduReader<'buf> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Condition code.
|
||||
#[inline]
|
||||
pub fn condition_code(&self) -> ConditionCode {
|
||||
self.condition_code
|
||||
}
|
||||
|
||||
/// Delivery code.
|
||||
#[inline]
|
||||
pub fn delivery_code(&self) -> DeliveryCode {
|
||||
self.delivery_code
|
||||
}
|
||||
|
||||
/// File status.
|
||||
#[inline]
|
||||
pub fn file_status(&self) -> FileStatus {
|
||||
self.file_status
|
||||
}
|
||||
|
||||
/// Optional fault location [EntityIdTlv].
|
||||
#[inline]
|
||||
pub fn fault_location(&self) -> Option<EntityIdTlv> {
|
||||
self.fault_location
|
||||
}
|
||||
|
||||
/// PDU header.
|
||||
#[inline]
|
||||
pub fn pdu_header(&self) -> &PduHeader {
|
||||
&self.pdu_header
|
||||
@@ -399,7 +424,7 @@ impl CfdpPdu for FinishedPduReader<'_> {
|
||||
|
||||
#[inline]
|
||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||
Some(FileDirectiveType::FinishedPdu)
|
||||
Some(FileDirectiveType::Finished)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,7 +493,7 @@ mod tests {
|
||||
assert_eq!(finished_pdu.pdu_type(), PduType::FileDirective);
|
||||
assert_eq!(
|
||||
finished_pdu.file_directive_type(),
|
||||
Some(FileDirectiveType::FinishedPdu)
|
||||
Some(FileDirectiveType::Finished)
|
||||
);
|
||||
assert_eq!(
|
||||
finished_pdu.transmission_mode(),
|
||||
@@ -500,7 +525,7 @@ mod tests {
|
||||
);
|
||||
verify_raw_header(finished_pdu.pdu_header(), &buf);
|
||||
let mut current_idx = finished_pdu.pdu_header().header_len();
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::FinishedPdu as u8);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::Finished as u8);
|
||||
current_idx += 1;
|
||||
assert_eq!(
|
||||
(buf[current_idx] >> 4) & 0b1111,
|
||||
@@ -626,7 +651,7 @@ mod tests {
|
||||
assert_eq!(finished_pdu_vec.len(), 12);
|
||||
assert_eq!(finished_pdu_vec[9], TlvType::EntityId.into());
|
||||
assert_eq!(finished_pdu_vec[10], 1);
|
||||
assert_eq!(finished_pdu_vec[11], TEST_DEST_ID.value_typed());
|
||||
assert_eq!(finished_pdu_vec[11], TEST_DEST_ID.value());
|
||||
assert_eq!(
|
||||
finished_pdu.fault_location().unwrap().entity_id(),
|
||||
&TEST_DEST_ID.into()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
//! # Metadata PDU packet implementation.
|
||||
#[cfg(feature = "alloc")]
|
||||
use super::tlv::TlvOwned;
|
||||
use crate::cfdp::lv::Lv;
|
||||
@@ -16,16 +17,21 @@ use serde::{Deserialize, Serialize};
|
||||
use super::tlv::ReadableTlv;
|
||||
use super::{CfdpPdu, WritablePduPacket};
|
||||
|
||||
/// Generic metadata parameters.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct MetadataGenericParams {
|
||||
/// Closure requested flag.
|
||||
pub closure_requested: bool,
|
||||
/// Checksum type.
|
||||
pub checksum_type: ChecksumType,
|
||||
/// File size.
|
||||
pub file_size: u64,
|
||||
}
|
||||
|
||||
impl MetadataGenericParams {
|
||||
/// Constructor.
|
||||
pub fn new(closure_requested: bool, checksum_type: ChecksumType, file_size: u64) -> Self {
|
||||
Self {
|
||||
closure_requested,
|
||||
@@ -35,6 +41,7 @@ impl MetadataGenericParams {
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the metadata options from a slice of [Tlv]s
|
||||
pub fn build_metadata_opts_from_slice(
|
||||
buf: &mut [u8],
|
||||
tlvs: &[Tlv],
|
||||
@@ -46,6 +53,7 @@ pub fn build_metadata_opts_from_slice(
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// Build the metadata options from a vector of [Tlv]s
|
||||
#[cfg(feature = "alloc")]
|
||||
pub fn build_metadata_opts_from_vec(
|
||||
buf: &mut [u8],
|
||||
@@ -54,6 +62,7 @@ pub fn build_metadata_opts_from_vec(
|
||||
build_metadata_opts_from_slice(buf, tlvs.as_slice())
|
||||
}
|
||||
|
||||
/// Build the metadata options from a slice of [TlvOwned]s
|
||||
#[cfg(feature = "alloc")]
|
||||
pub fn build_metadata_opts_from_owned_slice(tlvs: &[TlvOwned]) -> Vec<u8> {
|
||||
let mut sum_vec = Vec::new();
|
||||
@@ -77,6 +86,7 @@ pub struct MetadataPduCreator<'src_name, 'dest_name, 'opts> {
|
||||
}
|
||||
|
||||
impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'opts> {
|
||||
/// Constructor for a metadata PDU without options.
|
||||
pub fn new_no_opts(
|
||||
pdu_header: PduHeader,
|
||||
metadata_params: MetadataGenericParams,
|
||||
@@ -92,6 +102,7 @@ impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'op
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructor for a metadata PDU with options.
|
||||
pub fn new_with_opts(
|
||||
pdu_header: PduHeader,
|
||||
metadata_params: MetadataGenericParams,
|
||||
@@ -108,6 +119,7 @@ impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'op
|
||||
)
|
||||
}
|
||||
|
||||
/// Generic constructor for a metadata PDU.
|
||||
pub fn new(
|
||||
mut pdu_header: PduHeader,
|
||||
metadata_params: MetadataGenericParams,
|
||||
@@ -128,26 +140,31 @@ impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'op
|
||||
pdu
|
||||
}
|
||||
|
||||
/// Metadata generic parameters.
|
||||
#[inline]
|
||||
pub fn metadata_params(&self) -> &MetadataGenericParams {
|
||||
&self.metadata_params
|
||||
}
|
||||
|
||||
/// Source file name as a [Lv].
|
||||
#[inline]
|
||||
pub fn src_file_name(&self) -> Lv<'src_name> {
|
||||
self.src_file_name
|
||||
}
|
||||
|
||||
/// Destination file name as a [Lv].
|
||||
#[inline]
|
||||
pub fn dest_file_name(&self) -> Lv<'dest_name> {
|
||||
self.dest_file_name
|
||||
}
|
||||
|
||||
/// PDU header.
|
||||
#[inline]
|
||||
pub fn pdu_header(&self) -> &PduHeader {
|
||||
&self.pdu_header
|
||||
}
|
||||
|
||||
/// Raw options.
|
||||
#[inline]
|
||||
pub fn options(&self) -> &'opts [u8] {
|
||||
self.options
|
||||
@@ -191,7 +208,7 @@ impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'op
|
||||
}
|
||||
|
||||
let mut current_idx = self.pdu_header.write_to_bytes(buf)?;
|
||||
buf[current_idx] = FileDirectiveType::MetadataPdu as u8;
|
||||
buf[current_idx] = FileDirectiveType::Metadata as u8;
|
||||
current_idx += 1;
|
||||
buf[current_idx] = ((self.metadata_params.closure_requested as u8) << 6)
|
||||
| (self.metadata_params.checksum_type as u8);
|
||||
@@ -215,6 +232,7 @@ impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'op
|
||||
Ok(current_idx)
|
||||
}
|
||||
|
||||
/// Length of the written PDU in bytes.
|
||||
pub fn len_written(&self) -> usize {
|
||||
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||
}
|
||||
@@ -228,7 +246,7 @@ impl CfdpPdu for MetadataPduCreator<'_, '_, '_> {
|
||||
|
||||
#[inline]
|
||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||
Some(FileDirectiveType::MetadataPdu)
|
||||
Some(FileDirectiveType::Metadata)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,10 +309,12 @@ pub struct MetadataPduReader<'buf> {
|
||||
}
|
||||
|
||||
impl<'raw> MetadataPduReader<'raw> {
|
||||
/// Constructor from raw bytes.
|
||||
pub fn new(buf: &'raw [u8]) -> Result<Self, PduError> {
|
||||
Self::from_bytes(buf)
|
||||
}
|
||||
|
||||
/// Constructor from raw bytes.
|
||||
pub fn from_bytes(buf: &'raw [u8]) -> Result<Self, PduError> {
|
||||
let (pdu_header, mut current_idx) = PduHeader::from_bytes(buf)?;
|
||||
let full_len_without_crc = pdu_header.verify_length_and_checksum(buf)?;
|
||||
@@ -308,13 +328,13 @@ impl<'raw> MetadataPduReader<'raw> {
|
||||
let directive_type = FileDirectiveType::try_from(buf[current_idx]).map_err(|_| {
|
||||
PduError::InvalidDirectiveType {
|
||||
found: buf[current_idx],
|
||||
expected: Some(FileDirectiveType::MetadataPdu),
|
||||
expected: Some(FileDirectiveType::Metadata),
|
||||
}
|
||||
})?;
|
||||
if directive_type != FileDirectiveType::MetadataPdu {
|
||||
if directive_type != FileDirectiveType::Metadata {
|
||||
return Err(PduError::WrongDirectiveType {
|
||||
found: directive_type,
|
||||
expected: FileDirectiveType::MetadataPdu,
|
||||
expected: FileDirectiveType::Metadata,
|
||||
});
|
||||
}
|
||||
current_idx += 1;
|
||||
@@ -350,26 +370,31 @@ impl<'raw> MetadataPduReader<'raw> {
|
||||
})
|
||||
}
|
||||
|
||||
/// PDU header.
|
||||
#[inline]
|
||||
pub fn pdu_header(&self) -> &PduHeader {
|
||||
&self.pdu_header
|
||||
}
|
||||
|
||||
/// Raw options.
|
||||
#[inline]
|
||||
pub fn options(&self) -> &'raw [u8] {
|
||||
self.options
|
||||
}
|
||||
|
||||
/// Generic metadata parameters.
|
||||
#[inline]
|
||||
pub fn metadata_params(&self) -> &MetadataGenericParams {
|
||||
&self.metadata_params
|
||||
}
|
||||
|
||||
/// Source file name as a [Lv].
|
||||
#[inline]
|
||||
pub fn src_file_name(&self) -> Lv<'_> {
|
||||
self.src_file_name
|
||||
}
|
||||
|
||||
/// Destination file name as a [Lv].
|
||||
#[inline]
|
||||
pub fn dest_file_name(&self) -> Lv<'_> {
|
||||
self.dest_file_name
|
||||
@@ -383,12 +408,12 @@ impl CfdpPdu for MetadataPduReader<'_> {
|
||||
}
|
||||
|
||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||
Some(FileDirectiveType::MetadataPdu)
|
||||
Some(FileDirectiveType::Metadata)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
mod tests {
|
||||
use alloc::string::ToString;
|
||||
|
||||
use crate::cfdp::lv::Lv;
|
||||
@@ -471,7 +496,7 @@ pub mod tests {
|
||||
);
|
||||
assert_eq!(
|
||||
metadata_pdu.file_directive_type(),
|
||||
Some(FileDirectiveType::MetadataPdu)
|
||||
Some(FileDirectiveType::Metadata)
|
||||
);
|
||||
assert_eq!(
|
||||
metadata_pdu.transmission_mode(),
|
||||
@@ -502,7 +527,7 @@ pub mod tests {
|
||||
+ expected_src_filename.len_full()
|
||||
+ expected_dest_filename.len_full()
|
||||
);
|
||||
assert_eq!(buf[7], FileDirectiveType::MetadataPdu as u8);
|
||||
assert_eq!(buf[7], FileDirectiveType::Metadata as u8);
|
||||
assert_eq!(buf[8] >> 6, closure_requested as u8);
|
||||
assert_eq!(buf[8] & 0b1111, checksum_type as u8);
|
||||
assert_eq!(u32::from_be_bytes(buf[9..13].try_into().unwrap()), 0x1010);
|
||||
@@ -807,10 +832,10 @@ pub mod tests {
|
||||
let error = metadata_error.unwrap_err();
|
||||
if let PduError::InvalidDirectiveType { found, expected } = error {
|
||||
assert_eq!(found, 0xff);
|
||||
assert_eq!(expected, Some(FileDirectiveType::MetadataPdu));
|
||||
assert_eq!(expected, Some(FileDirectiveType::Metadata));
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"invalid directive type, found 255, expected Some(MetadataPdu)"
|
||||
"invalid directive type, found 255, expected Some(Metadata)"
|
||||
);
|
||||
} else {
|
||||
panic!("Expected InvalidDirectiveType error, got {:?}", error);
|
||||
@@ -827,16 +852,16 @@ pub mod tests {
|
||||
&[],
|
||||
);
|
||||
let mut metadata_vec = metadata_pdu.to_vec().unwrap();
|
||||
metadata_vec[7] = FileDirectiveType::EofPdu as u8;
|
||||
metadata_vec[7] = FileDirectiveType::Eof as u8;
|
||||
let metadata_error = MetadataPduReader::from_bytes(&metadata_vec);
|
||||
assert!(metadata_error.is_err());
|
||||
let error = metadata_error.unwrap_err();
|
||||
if let PduError::WrongDirectiveType { found, expected } = error {
|
||||
assert_eq!(found, FileDirectiveType::EofPdu);
|
||||
assert_eq!(expected, FileDirectiveType::MetadataPdu);
|
||||
assert_eq!(found, FileDirectiveType::Eof);
|
||||
assert_eq!(expected, FileDirectiveType::Metadata);
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"wrong directive type, found EofPdu, expected MetadataPdu"
|
||||
"wrong directive type, found Eof, expected Metadata"
|
||||
);
|
||||
} else {
|
||||
panic!("Expected InvalidDirectiveType error, got {:?}", error);
|
||||
|
||||
@@ -15,24 +15,34 @@ pub mod finished;
|
||||
pub mod metadata;
|
||||
pub mod nak;
|
||||
|
||||
/// File directive type.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum FileDirectiveType {
|
||||
EofPdu = 0x04,
|
||||
FinishedPdu = 0x05,
|
||||
AckPdu = 0x06,
|
||||
MetadataPdu = 0x07,
|
||||
NakPdu = 0x08,
|
||||
PromptPdu = 0x09,
|
||||
KeepAlivePdu = 0x0c,
|
||||
/// EOF.
|
||||
Eof = 0x04,
|
||||
/// Finished.
|
||||
Finished = 0x05,
|
||||
/// ACK.
|
||||
Ack = 0x06,
|
||||
/// Metadata.
|
||||
Metadata = 0x07,
|
||||
/// NAK.
|
||||
Nak = 0x08,
|
||||
/// Prompt.
|
||||
Prompt = 0x09,
|
||||
/// Keep Alive.
|
||||
KeepAlive = 0x0c,
|
||||
}
|
||||
|
||||
/// PDU error.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum PduError {
|
||||
/// Byte conversion error.
|
||||
#[error("byte conversion error: {0}")]
|
||||
ByteConversion(#[from] ByteConversionError),
|
||||
/// Found version ID invalid, not equal to [super::CFDP_VERSION_2].
|
||||
@@ -44,27 +54,35 @@ pub enum PduError {
|
||||
/// Invalid length for the entity ID detected. Only the values 1, 2, 4 and 8 are supported.
|
||||
#[error("invalid transaction ID length {0}")]
|
||||
InvalidTransactionSeqNumLen(u8),
|
||||
/// Source and destination entity ID lengths do not match.
|
||||
#[error(
|
||||
"missmatch of PDU source ID length {src_id_len} and destination ID length {dest_id_len}"
|
||||
)]
|
||||
SourceDestIdLenMissmatch {
|
||||
/// Source ID length.
|
||||
src_id_len: usize,
|
||||
/// Destination ID length.
|
||||
dest_id_len: usize,
|
||||
},
|
||||
/// Wrong directive type, for example when parsing the directive field for a file directive
|
||||
/// PDU.
|
||||
#[error("wrong directive type, found {found:?}, expected {expected:?}")]
|
||||
WrongDirectiveType {
|
||||
/// Found directive type.
|
||||
found: FileDirectiveType,
|
||||
/// Expected directive type.
|
||||
expected: FileDirectiveType,
|
||||
},
|
||||
/// The directive type field contained a value not in the range of permitted values. This can
|
||||
/// also happen if an invalid value is passed to the ACK PDU reader.
|
||||
#[error("invalid directive type, found {found:?}, expected {expected:?}")]
|
||||
InvalidDirectiveType {
|
||||
/// Found raw directive type.
|
||||
found: u8,
|
||||
/// Expected raw directive type if applicable.
|
||||
expected: Option<FileDirectiveType>,
|
||||
},
|
||||
/// Invalid start or end of scope for a NAK PDU.
|
||||
#[error("nak pdu: {0}")]
|
||||
InvalidStartOrEndOfScope(#[from] InvalidStartOrEndOfScopeError),
|
||||
/// Invalid condition code. Contains the raw detected value.
|
||||
@@ -74,6 +92,7 @@ pub enum PduError {
|
||||
/// [SANA Checksum Types registry](https://sanaregistry.org/r/checksum_identifiers/).
|
||||
#[error("invalid checksum type {0}")]
|
||||
InvalidChecksumType(u8),
|
||||
/// File size is too large.
|
||||
#[error("file size {0} too large")]
|
||||
FileSizeTooLarge(u64),
|
||||
/// If the CRC flag for a PDU is enabled and the checksum check fails. Contains raw 16-bit CRC.
|
||||
@@ -96,9 +115,15 @@ impl From<InvalidAckedDirectiveCodeError> for PduError {
|
||||
}
|
||||
}
|
||||
|
||||
/// Generic trait for a PDU which can be written to bytes.
|
||||
pub trait WritablePduPacket {
|
||||
/// Length when written to bytes.
|
||||
fn len_written(&self) -> usize;
|
||||
|
||||
/// Write the PDU to a raw buffer, returning the written length.
|
||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError>;
|
||||
|
||||
/// Convert the PDU to an owned vector of bytes.
|
||||
#[cfg(feature = "alloc")]
|
||||
fn to_vec(&self) -> Result<Vec<u8>, PduError> {
|
||||
// This is the correct way to do this. See
|
||||
@@ -112,48 +137,58 @@ pub trait WritablePduPacket {
|
||||
|
||||
/// Abstraction trait for fields and properties common for all PDUs.
|
||||
pub trait CfdpPdu {
|
||||
/// PDU header.
|
||||
fn pdu_header(&self) -> &PduHeader;
|
||||
|
||||
/// Source ID (file sender).
|
||||
#[inline]
|
||||
fn source_id(&self) -> UnsignedByteField {
|
||||
self.pdu_header().common_pdu_conf().source_entity_id
|
||||
}
|
||||
|
||||
/// Destination ID (file sender).
|
||||
#[inline]
|
||||
fn dest_id(&self) -> UnsignedByteField {
|
||||
self.pdu_header().common_pdu_conf().dest_entity_id
|
||||
}
|
||||
|
||||
/// Transaction sequence number.
|
||||
#[inline]
|
||||
fn transaction_seq_num(&self) -> UnsignedByteField {
|
||||
self.pdu_header().common_pdu_conf().transaction_seq_num
|
||||
}
|
||||
|
||||
/// Transmission mode.
|
||||
#[inline]
|
||||
fn transmission_mode(&self) -> TransmissionMode {
|
||||
self.pdu_header().common_pdu_conf().trans_mode
|
||||
}
|
||||
|
||||
/// Direction.
|
||||
#[inline]
|
||||
fn direction(&self) -> Direction {
|
||||
self.pdu_header().common_pdu_conf().direction
|
||||
}
|
||||
|
||||
/// CRC flag.
|
||||
#[inline]
|
||||
fn crc_flag(&self) -> CrcFlag {
|
||||
self.pdu_header().common_pdu_conf().crc_flag
|
||||
}
|
||||
|
||||
/// File flag.
|
||||
#[inline]
|
||||
fn file_flag(&self) -> LargeFileFlag {
|
||||
self.pdu_header().common_pdu_conf().file_flag
|
||||
}
|
||||
|
||||
/// PDU type.
|
||||
#[inline]
|
||||
fn pdu_type(&self) -> PduType {
|
||||
self.pdu_header().pdu_type()
|
||||
}
|
||||
|
||||
/// File directive type when applicable.
|
||||
fn file_directive_type(&self) -> Option<FileDirectiveType>;
|
||||
}
|
||||
|
||||
@@ -169,15 +204,21 @@ pub trait CfdpPdu {
|
||||
pub struct CommonPduConfig {
|
||||
source_entity_id: UnsignedByteField,
|
||||
dest_entity_id: UnsignedByteField,
|
||||
/// Transaction sequence number.
|
||||
pub transaction_seq_num: UnsignedByteField,
|
||||
/// Transmission mode.
|
||||
pub trans_mode: TransmissionMode,
|
||||
/// File flag.
|
||||
pub file_flag: LargeFileFlag,
|
||||
/// CRC flag.
|
||||
pub crc_flag: CrcFlag,
|
||||
/// Direction.
|
||||
pub direction: Direction,
|
||||
}
|
||||
|
||||
// TODO: Builder pattern might be applicable here..
|
||||
impl CommonPduConfig {
|
||||
/// Generic constructor.
|
||||
#[inline]
|
||||
pub fn new(
|
||||
source_id: impl Into<UnsignedByteField>,
|
||||
@@ -210,6 +251,7 @@ impl CommonPduConfig {
|
||||
})
|
||||
}
|
||||
|
||||
/// Constructor for custom byte field with default field values for the other fields.
|
||||
#[inline]
|
||||
pub fn new_with_byte_fields(
|
||||
source_id: impl Into<UnsignedByteField>,
|
||||
@@ -227,6 +269,7 @@ impl CommonPduConfig {
|
||||
)
|
||||
}
|
||||
|
||||
/// Source ID (file sender).
|
||||
#[inline]
|
||||
pub fn source_id(&self) -> UnsignedByteField {
|
||||
self.source_entity_id
|
||||
@@ -255,6 +298,7 @@ impl CommonPduConfig {
|
||||
Ok((source_id, dest_id))
|
||||
}
|
||||
|
||||
/// Set the source and destination ID field.
|
||||
#[inline]
|
||||
pub fn set_source_and_dest_id(
|
||||
&mut self,
|
||||
@@ -267,6 +311,7 @@ impl CommonPduConfig {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Destination ID (file receiver).
|
||||
#[inline]
|
||||
pub fn dest_id(&self) -> UnsignedByteField {
|
||||
self.dest_entity_id
|
||||
@@ -305,6 +350,7 @@ impl PartialEq for CommonPduConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixed header length of the PDU header.
|
||||
pub const FIXED_HEADER_LEN: usize = 4;
|
||||
|
||||
/// Abstraction for the PDU header common to all CFDP PDUs.
|
||||
@@ -322,8 +368,10 @@ pub struct PduHeader {
|
||||
}
|
||||
|
||||
impl PduHeader {
|
||||
/// Fixed length of the PDU header when written to a raw buffer.
|
||||
pub const FIXED_LEN: usize = FIXED_HEADER_LEN;
|
||||
|
||||
/// Constructor for a File Data PDU header.
|
||||
#[inline]
|
||||
pub fn new_for_file_data(
|
||||
pdu_conf: CommonPduConfig,
|
||||
@@ -340,6 +388,7 @@ impl PduHeader {
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructor for a file data PDU.
|
||||
#[inline]
|
||||
pub fn new_for_file_data_default(pdu_conf: CommonPduConfig, pdu_datafield_len: u16) -> Self {
|
||||
Self::new_generic(
|
||||
@@ -351,6 +400,7 @@ impl PduHeader {
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructor for a file directive PDU.
|
||||
#[inline]
|
||||
pub fn new_for_file_directive(pdu_conf: CommonPduConfig, pdu_datafield_len: u16) -> Self {
|
||||
Self::new_generic(
|
||||
@@ -362,6 +412,7 @@ impl PduHeader {
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructor from a given [CommonPduConfig] and for a file directive PDU.
|
||||
#[inline]
|
||||
pub fn from_pdu_conf_for_file_directive(pdu_conf: CommonPduConfig) -> Self {
|
||||
Self::new_generic(
|
||||
@@ -373,6 +424,7 @@ impl PduHeader {
|
||||
)
|
||||
}
|
||||
|
||||
/// Generic constructor.
|
||||
#[inline]
|
||||
pub fn new_generic(
|
||||
pdu_type: PduType,
|
||||
@@ -399,6 +451,7 @@ impl PduHeader {
|
||||
+ self.pdu_conf.dest_entity_id.size()
|
||||
}
|
||||
|
||||
/// PDU data field length.
|
||||
#[inline]
|
||||
pub fn pdu_datafield_len(&self) -> usize {
|
||||
self.pdu_datafield_len.into()
|
||||
@@ -411,6 +464,7 @@ impl PduHeader {
|
||||
self.header_len() + self.pdu_datafield_len as usize
|
||||
}
|
||||
|
||||
/// Write the header to a raw buffer, returning the written length on success.
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
// The API does not allow passing entity IDs with different sizes, so this should
|
||||
// never happen.
|
||||
@@ -578,21 +632,25 @@ impl PduHeader {
|
||||
))
|
||||
}
|
||||
|
||||
/// PDU type.
|
||||
#[inline]
|
||||
pub fn pdu_type(&self) -> PduType {
|
||||
self.pdu_type
|
||||
}
|
||||
|
||||
/// Common PDU configuration fields.
|
||||
#[inline]
|
||||
pub fn common_pdu_conf(&self) -> &CommonPduConfig {
|
||||
&self.pdu_conf
|
||||
}
|
||||
|
||||
/// Segment metadata flag.
|
||||
#[inline]
|
||||
pub fn seg_metadata_flag(&self) -> SegmentMetadataFlag {
|
||||
self.seg_metadata_flag
|
||||
}
|
||||
|
||||
/// Segmentation Control.
|
||||
#[inline]
|
||||
pub fn seg_ctrl(&self) -> SegmentationControl {
|
||||
self.seg_ctrl
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
//! # NAK PDU packet implementation.
|
||||
use crate::{
|
||||
cfdp::{CrcFlag, Direction, LargeFileFlag},
|
||||
ByteConversionError,
|
||||
@@ -8,6 +9,7 @@ use super::{
|
||||
PduHeader, WritablePduPacket,
|
||||
};
|
||||
|
||||
/// Invalid start or end of scope value.
|
||||
#[derive(Debug, PartialEq, Eq, Copy, Clone, thiserror::Error)]
|
||||
#[error("invalid start or end of scope value for NAK PDU")]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -52,6 +54,7 @@ fn write_start_and_end_of_scope(
|
||||
current_index
|
||||
}
|
||||
|
||||
/// Buffer is too small to even hold a PDU header.
|
||||
#[derive(Debug, PartialEq, Eq, Copy, Clone, thiserror::Error)]
|
||||
#[error("packet buffer too small for PDU header")]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -94,11 +97,14 @@ pub fn calculate_max_segment_requests(
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum SegmentRequests<'a> {
|
||||
/// Segment requests for normal file sizes bounded by [u32::MAX].
|
||||
U32Pairs(&'a [(u32, u32)]),
|
||||
/// Segment requests for large file sizes bounded by [u64::MAX].
|
||||
U64Pairs(&'a [(u64, u64)]),
|
||||
}
|
||||
|
||||
impl SegmentRequests<'_> {
|
||||
/// Wrapped segment requests are empty.
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
match self {
|
||||
@@ -152,6 +158,7 @@ impl<'seg_reqs> NakPduCreator<'seg_reqs> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructor for large file sizes.
|
||||
pub fn new_large_file_size(
|
||||
pdu_header: PduHeader,
|
||||
start_of_scope: u64,
|
||||
@@ -206,21 +213,25 @@ impl<'seg_reqs> NakPduCreator<'seg_reqs> {
|
||||
Ok(nak_pdu)
|
||||
}
|
||||
|
||||
/// Start of scope of the NAK PDU.
|
||||
#[inline]
|
||||
pub fn start_of_scope(&self) -> u64 {
|
||||
self.start_of_scope
|
||||
}
|
||||
|
||||
/// End of scope of the NAK PDU.
|
||||
#[inline]
|
||||
pub fn end_of_scope(&self) -> u64 {
|
||||
self.end_of_scope
|
||||
}
|
||||
|
||||
/// Semgent requests.
|
||||
#[inline]
|
||||
pub fn segment_requests(&self) -> Option<&SegmentRequests<'_>> {
|
||||
self.segment_requests.as_ref()
|
||||
}
|
||||
|
||||
/// Number of segment requests.
|
||||
#[inline]
|
||||
pub fn num_segment_reqs(&self) -> usize {
|
||||
match &self.segment_requests {
|
||||
@@ -232,6 +243,7 @@ impl<'seg_reqs> NakPduCreator<'seg_reqs> {
|
||||
}
|
||||
}
|
||||
|
||||
/// PDU header.
|
||||
#[inline]
|
||||
pub fn pdu_header(&self) -> &PduHeader {
|
||||
&self.pdu_header
|
||||
@@ -252,7 +264,7 @@ impl<'seg_reqs> NakPduCreator<'seg_reqs> {
|
||||
.into());
|
||||
}
|
||||
let mut current_index = self.pdu_header.write_to_bytes(buf)?;
|
||||
buf[current_index] = FileDirectiveType::NakPdu as u8;
|
||||
buf[current_index] = FileDirectiveType::Nak as u8;
|
||||
current_index += 1;
|
||||
|
||||
current_index = write_start_and_end_of_scope(
|
||||
@@ -309,7 +321,7 @@ impl CfdpPdu for NakPduCreator<'_> {
|
||||
|
||||
#[inline]
|
||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||
Some(FileDirectiveType::NakPdu)
|
||||
Some(FileDirectiveType::Nak)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -337,6 +349,8 @@ pub struct NakPduCreatorWithReservedSeqReqsBuf<'buf> {
|
||||
}
|
||||
|
||||
impl<'buf> NakPduCreatorWithReservedSeqReqsBuf<'buf> {
|
||||
/// Calculartes the maximum amount of segment requests which fit into a packet with the
|
||||
/// provided parameters.
|
||||
pub fn calculate_max_segment_requests(
|
||||
max_packet_size: usize,
|
||||
pdu_header: &PduHeader,
|
||||
@@ -344,6 +358,7 @@ impl<'buf> NakPduCreatorWithReservedSeqReqsBuf<'buf> {
|
||||
calculate_max_segment_requests(max_packet_size, pdu_header)
|
||||
}
|
||||
|
||||
/// Constructor.
|
||||
pub fn new(
|
||||
buf: &'buf mut [u8],
|
||||
mut pdu_header: PduHeader,
|
||||
@@ -371,11 +386,13 @@ impl<'buf> NakPduCreatorWithReservedSeqReqsBuf<'buf> {
|
||||
}
|
||||
|
||||
impl NakPduCreatorWithReservedSeqReqsBuf<'_> {
|
||||
/// PDU header.
|
||||
#[inline]
|
||||
pub fn pdu_header(&self) -> &PduHeader {
|
||||
&self.pdu_header
|
||||
}
|
||||
|
||||
/// Number of segment requests.
|
||||
#[inline]
|
||||
pub fn num_segment_reqs(&self) -> usize {
|
||||
self.num_segment_reqs
|
||||
@@ -407,6 +424,7 @@ impl NakPduCreatorWithReservedSeqReqsBuf<'_> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Length when written to a buffer.
|
||||
pub fn len_written(&self) -> usize {
|
||||
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||
}
|
||||
@@ -427,6 +445,7 @@ impl NakPduCreatorWithReservedSeqReqsBuf<'_> {
|
||||
&self.buf[segment_req_buf_offset..segment_req_buf_offset + len]
|
||||
}
|
||||
|
||||
/// Iterator over all segment requests.
|
||||
#[inline]
|
||||
pub fn segment_request_iter(&self) -> SegmentRequestIter<'_> {
|
||||
SegmentRequestIter::new(
|
||||
@@ -447,7 +466,7 @@ impl NakPduCreatorWithReservedSeqReqsBuf<'_> {
|
||||
) -> Result<usize, InvalidStartOrEndOfScopeError> {
|
||||
self.set_start_and_end_of_scope(start_of_scope, end_of_scope)?;
|
||||
let mut current_idx = self.pdu_header.write_to_bytes(self.buf).unwrap();
|
||||
self.buf[current_idx] = FileDirectiveType::NakPdu as u8;
|
||||
self.buf[current_idx] = FileDirectiveType::Nak as u8;
|
||||
current_idx += 1;
|
||||
|
||||
if self.pdu_header.common_pdu_conf().file_flag == LargeFileFlag::Large {
|
||||
@@ -613,15 +632,17 @@ impl CfdpPdu for NakPduReader<'_> {
|
||||
}
|
||||
|
||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||
Some(FileDirectiveType::NakPdu)
|
||||
Some(FileDirectiveType::Nak)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'seg_reqs> NakPduReader<'seg_reqs> {
|
||||
/// Constructor from a raw bytestream.
|
||||
pub fn new(buf: &'seg_reqs [u8]) -> Result<NakPduReader<'seg_reqs>, PduError> {
|
||||
Self::from_bytes(buf)
|
||||
}
|
||||
|
||||
/// Constructor from a raw bytestream.
|
||||
pub fn from_bytes(buf: &'seg_reqs [u8]) -> Result<NakPduReader<'seg_reqs>, PduError> {
|
||||
let (pdu_header, mut current_idx) = PduHeader::from_bytes(buf)?;
|
||||
let full_len_without_crc = pdu_header.verify_length_and_checksum(buf)?;
|
||||
@@ -631,13 +652,13 @@ impl<'seg_reqs> NakPduReader<'seg_reqs> {
|
||||
let directive_type = FileDirectiveType::try_from(buf[current_idx]).map_err(|_| {
|
||||
PduError::InvalidDirectiveType {
|
||||
found: buf[current_idx],
|
||||
expected: Some(FileDirectiveType::NakPdu),
|
||||
expected: Some(FileDirectiveType::Nak),
|
||||
}
|
||||
})?;
|
||||
if directive_type != FileDirectiveType::NakPdu {
|
||||
if directive_type != FileDirectiveType::Nak {
|
||||
return Err(PduError::WrongDirectiveType {
|
||||
found: directive_type,
|
||||
expected: FileDirectiveType::AckPdu,
|
||||
expected: FileDirectiveType::Ack,
|
||||
});
|
||||
}
|
||||
current_idx += 1;
|
||||
@@ -682,14 +703,17 @@ impl<'seg_reqs> NakPduReader<'seg_reqs> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Start of scope.
|
||||
pub fn start_of_scope(&self) -> u64 {
|
||||
self.start_of_scope
|
||||
}
|
||||
|
||||
/// End of scope.
|
||||
pub fn end_of_scope(&self) -> u64 {
|
||||
self.end_of_scope
|
||||
}
|
||||
|
||||
/// Number of segment requests.
|
||||
pub fn num_segment_reqs(&self) -> usize {
|
||||
if self.seg_reqs_raw.is_empty() {
|
||||
return 0;
|
||||
@@ -747,10 +771,7 @@ mod tests {
|
||||
assert_eq!(nak_pdu.crc_flag(), CrcFlag::NoCrc);
|
||||
assert_eq!(nak_pdu.file_flag(), LargeFileFlag::Normal);
|
||||
assert_eq!(nak_pdu.pdu_type(), PduType::FileDirective);
|
||||
assert_eq!(
|
||||
nak_pdu.file_directive_type(),
|
||||
Some(FileDirectiveType::NakPdu),
|
||||
);
|
||||
assert_eq!(nak_pdu.file_directive_type(), Some(FileDirectiveType::Nak),);
|
||||
assert_eq!(nak_pdu.transmission_mode(), TransmissionMode::Acknowledged);
|
||||
assert_eq!(nak_pdu.direction(), Direction::TowardsSender);
|
||||
assert_eq!(nak_pdu.source_id(), TEST_SRC_ID.into());
|
||||
@@ -794,7 +815,7 @@ mod tests {
|
||||
verify_raw_header(nak_pdu.pdu_header(), &buf);
|
||||
let mut current_idx = nak_pdu.pdu_header().header_len();
|
||||
assert_eq!(current_idx + 9, nak_pdu.len_written());
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::NakPdu as u8);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::Nak as u8);
|
||||
current_idx += 1;
|
||||
let start_of_scope =
|
||||
u32::from_be_bytes(buf[current_idx..current_idx + 4].try_into().unwrap());
|
||||
@@ -821,7 +842,7 @@ mod tests {
|
||||
verify_raw_header(nak_pdu.pdu_header(), &buf);
|
||||
let mut current_idx = nak_pdu.pdu_header().header_len();
|
||||
assert_eq!(current_idx + 9 + 16, nak_pdu.len_written());
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::NakPdu as u8);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::Nak as u8);
|
||||
current_idx += 1;
|
||||
let start_of_scope =
|
||||
u32::from_be_bytes(buf[current_idx..current_idx + 4].try_into().unwrap());
|
||||
@@ -1034,7 +1055,7 @@ mod tests {
|
||||
verify_raw_header(&pdu_header, &buf);
|
||||
let mut current_idx = pdu_header.header_len();
|
||||
assert_eq!(current_idx + 9, len_written);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::NakPdu as u8);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::Nak as u8);
|
||||
current_idx += 1;
|
||||
let start_of_scope =
|
||||
u32::from_be_bytes(buf[current_idx..current_idx + 4].try_into().unwrap());
|
||||
@@ -1060,7 +1081,7 @@ mod tests {
|
||||
verify_raw_header(&pdu_header, &buf);
|
||||
let mut current_idx = pdu_header.header_len();
|
||||
assert_eq!(current_idx + 1 + 8 + 2, len_written);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::NakPdu as u8);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::Nak as u8);
|
||||
current_idx += 1;
|
||||
let start_of_scope =
|
||||
u32::from_be_bytes(buf[current_idx..current_idx + 4].try_into().unwrap());
|
||||
@@ -1087,7 +1108,7 @@ mod tests {
|
||||
verify_raw_header(&pdu_header, &buf);
|
||||
let mut current_idx = pdu_header.header_len();
|
||||
assert_eq!(current_idx + 1 + 16, len_written);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::NakPdu as u8);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::Nak as u8);
|
||||
current_idx += 1;
|
||||
let start_of_scope =
|
||||
u64::from_be_bytes(buf[current_idx..current_idx + 8].try_into().unwrap());
|
||||
@@ -1131,7 +1152,7 @@ mod tests {
|
||||
verify_raw_header(&pdu_header, &buf);
|
||||
let mut current_idx = pdu_header.header_len();
|
||||
assert_eq!(current_idx + 1 + 16, len_written);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::NakPdu as u8);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::Nak as u8);
|
||||
current_idx += 1;
|
||||
let start_of_scope =
|
||||
u64::from_be_bytes(buf[current_idx..current_idx + 8].try_into().unwrap());
|
||||
@@ -1171,7 +1192,7 @@ mod tests {
|
||||
verify_raw_header(&pdu_header, &buf);
|
||||
let mut current_idx = pdu_header.header_len();
|
||||
assert_eq!(current_idx + 1 + 8 + num_segments * 8, len_written);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::NakPdu as u8);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::Nak as u8);
|
||||
current_idx += 1;
|
||||
let start_of_scope =
|
||||
u32::from_be_bytes(buf[current_idx..current_idx + 4].try_into().unwrap());
|
||||
@@ -1227,7 +1248,7 @@ mod tests {
|
||||
verify_raw_header(&pdu_header, &buf);
|
||||
let mut current_idx = pdu_header.header_len();
|
||||
assert_eq!(current_idx + 1 + 16 + num_segments * 16, len_written);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::NakPdu as u8);
|
||||
assert_eq!(buf[current_idx], FileDirectiveType::Nak as u8);
|
||||
current_idx += 1;
|
||||
let start_of_scope =
|
||||
u64::from_be_bytes(buf[current_idx..current_idx + 8].try_into().unwrap());
|
||||
|
||||
@@ -19,9 +19,12 @@ use super::{InvalidTlvTypeFieldError, TlvLvDataTooLargeError};
|
||||
|
||||
pub mod msg_to_user;
|
||||
|
||||
/// Minimum length of a type-length-value structure, including type and length fields.
|
||||
pub const MIN_TLV_LEN: usize = 2;
|
||||
|
||||
/// Trait for generic TLV structures.
|
||||
pub trait GenericTlv {
|
||||
/// TLV type field.
|
||||
fn tlv_type_field(&self) -> TlvTypeField;
|
||||
|
||||
/// Checks whether the type field contains one of the standard types specified in the CFDP
|
||||
@@ -45,7 +48,9 @@ pub trait GenericTlv {
|
||||
}
|
||||
}
|
||||
|
||||
/// Readable TLV structure trait.
|
||||
pub trait ReadableTlv {
|
||||
/// Value field of the TLV.
|
||||
fn value(&self) -> &[u8];
|
||||
|
||||
/// Checks whether the value field is empty.
|
||||
@@ -68,9 +73,15 @@ pub trait ReadableTlv {
|
||||
}
|
||||
}
|
||||
|
||||
/// Writable TLV structure trait.
|
||||
pub trait WritableTlv {
|
||||
/// Write the TLV to bytes.
|
||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;
|
||||
|
||||
/// Length of the written TLV.
|
||||
fn len_written(&self) -> usize;
|
||||
|
||||
/// Convenience method to write the TLV to an owned [alloc::vec::Vec].
|
||||
#[cfg(feature = "alloc")]
|
||||
fn to_vec(&self) -> Vec<u8> {
|
||||
let mut buf = vec![0; self.len_written()];
|
||||
@@ -79,34 +90,50 @@ pub trait WritableTlv {
|
||||
}
|
||||
}
|
||||
|
||||
/// TLV type.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum TlvType {
|
||||
/// Filestore request.
|
||||
FilestoreRequest = 0x00,
|
||||
/// Filestore response.
|
||||
FilestoreResponse = 0x01,
|
||||
/// Message to user.
|
||||
MsgToUser = 0x02,
|
||||
/// Fault handler.
|
||||
FaultHandler = 0x04,
|
||||
/// Flow label.
|
||||
FlowLabel = 0x05,
|
||||
/// Entity ID.
|
||||
EntityId = 0x06,
|
||||
}
|
||||
|
||||
/// TLV type field variants.
|
||||
///
|
||||
/// This allows specifying custom variants as well.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum TlvTypeField {
|
||||
/// Standard TLV types.
|
||||
Standard(TlvType),
|
||||
/// Custom TLV type.
|
||||
Custom(u8),
|
||||
}
|
||||
|
||||
/// Filestore action codes as specified in the standard.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum FilestoreActionCode {
|
||||
/// Create file.
|
||||
CreateFile = 0b0000,
|
||||
/// Delete file.
|
||||
DeleteFile = 0b0001,
|
||||
/// Rename file.
|
||||
RenameFile = 0b0010,
|
||||
/// This operation appends one file to another. The first specified name will form the first
|
||||
/// part of the new file and the name of the new file. This function can be used to get
|
||||
@@ -115,9 +142,13 @@ pub enum FilestoreActionCode {
|
||||
/// This operation replaces the content of the first specified file with the content of
|
||||
/// the secondly specified file.
|
||||
ReplaceFile = 0b0100,
|
||||
/// Create directory.
|
||||
CreateDirectory = 0b0101,
|
||||
/// Remove directory.
|
||||
RemoveDirectory = 0b0110,
|
||||
/// Deny file.
|
||||
DenyFile = 0b0111,
|
||||
/// Deny directory.
|
||||
DenyDirectory = 0b1000,
|
||||
}
|
||||
|
||||
@@ -158,8 +189,10 @@ pub struct Tlv<'data> {
|
||||
}
|
||||
|
||||
impl<'data> Tlv<'data> {
|
||||
/// Minimum length of a TLV structure, including type and length fields.
|
||||
pub const MIN_LEN: usize = MIN_TLV_LEN;
|
||||
|
||||
/// Generic constructor for a TLV structure.
|
||||
pub fn new(tlv_type: TlvType, data: &[u8]) -> Result<Tlv<'_>, TlvLvDataTooLargeError> {
|
||||
Ok(Tlv {
|
||||
tlv_type_field: TlvTypeField::Standard(tlv_type),
|
||||
@@ -167,6 +200,7 @@ impl<'data> Tlv<'data> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Constructor for a TLV with a custom type field.
|
||||
pub fn new_with_custom_type(
|
||||
tlv_type: u8,
|
||||
data: &[u8],
|
||||
@@ -208,6 +242,7 @@ impl<'data> Tlv<'data> {
|
||||
self.lv.raw_data()
|
||||
}
|
||||
|
||||
/// Converts to an owned TLV variant, allocating memory for the value field.
|
||||
#[cfg(feature = "alloc")]
|
||||
pub fn to_owned(&self) -> TlvOwned {
|
||||
TlvOwned {
|
||||
@@ -251,6 +286,7 @@ impl GenericTlv for Tlv<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Component of the TLV module which require [alloc] support.
|
||||
#[cfg(feature = "alloc")]
|
||||
pub mod alloc_mod {
|
||||
use super::*;
|
||||
@@ -266,6 +302,7 @@ pub mod alloc_mod {
|
||||
}
|
||||
|
||||
impl TlvOwned {
|
||||
/// Generic constructor.
|
||||
pub fn new(tlv_type: TlvType, data: &[u8]) -> Self {
|
||||
Self {
|
||||
tlv_type_field: TlvTypeField::Standard(tlv_type),
|
||||
@@ -273,6 +310,7 @@ pub mod alloc_mod {
|
||||
}
|
||||
}
|
||||
|
||||
/// Generic constructor with a custom TLV type.
|
||||
pub fn new_with_custom_type(tlv_type: u8, data: &[u8]) -> Self {
|
||||
Self {
|
||||
tlv_type_field: TlvTypeField::Custom(tlv_type),
|
||||
@@ -288,6 +326,7 @@ pub mod alloc_mod {
|
||||
}
|
||||
}
|
||||
|
||||
/// Write to a byte slice.
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
generic_len_check_data_serialization(buf, self.data.len(), MIN_TLV_LEN)?;
|
||||
buf[0] = self.tlv_type_field.into();
|
||||
@@ -301,6 +340,7 @@ pub mod alloc_mod {
|
||||
self.data.len() + 2
|
||||
}
|
||||
|
||||
/// Convert to [Tlv]
|
||||
pub fn as_tlv(&self) -> Tlv<'_> {
|
||||
Tlv {
|
||||
tlv_type_field: self.tlv_type_field,
|
||||
@@ -349,6 +389,7 @@ pub mod alloc_mod {
|
||||
}
|
||||
}
|
||||
|
||||
/// Entity ID TLV.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -357,6 +398,7 @@ pub struct EntityIdTlv {
|
||||
}
|
||||
|
||||
impl EntityIdTlv {
|
||||
/// Constructor.
|
||||
#[inline]
|
||||
pub fn new(entity_id: UnsignedByteField) -> Self {
|
||||
Self { entity_id }
|
||||
@@ -372,21 +414,25 @@ impl EntityIdTlv {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Entity ID.
|
||||
#[inline]
|
||||
pub fn entity_id(&self) -> &UnsignedByteField {
|
||||
&self.entity_id
|
||||
}
|
||||
|
||||
/// Length of the value field.
|
||||
#[inline]
|
||||
pub fn len_value(&self) -> usize {
|
||||
self.entity_id.size()
|
||||
}
|
||||
|
||||
/// Full length of the TLV, including type and length fields.
|
||||
#[inline]
|
||||
pub fn len_full(&self) -> usize {
|
||||
2 + self.entity_id.size()
|
||||
}
|
||||
|
||||
/// Create from a raw bytestream.
|
||||
pub fn from_bytes(buf: &[u8]) -> Result<Self, TlvLvError> {
|
||||
Self::len_check(buf)?;
|
||||
verify_tlv_type(buf[0], TlvType::EntityId)?;
|
||||
@@ -478,6 +524,7 @@ impl TryFrom<Tlv<'_>> for EntityIdTlv {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the [FilestoreActionCode] have a second filename?
|
||||
#[inline]
|
||||
pub fn fs_request_has_second_filename(action_code: FilestoreActionCode) -> bool {
|
||||
if action_code == FilestoreActionCode::RenameFile
|
||||
@@ -511,6 +558,7 @@ impl FilestoreTlvBase<'_, '_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Filestore request TLV.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct FilestoreRequestTlv<'first_name, 'second_name> {
|
||||
@@ -519,14 +567,17 @@ pub struct FilestoreRequestTlv<'first_name, 'second_name> {
|
||||
}
|
||||
|
||||
impl<'first_name, 'second_name> FilestoreRequestTlv<'first_name, 'second_name> {
|
||||
/// Constructor for file creation.
|
||||
pub fn new_create_file(file_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
|
||||
Self::new(FilestoreActionCode::CreateFile, file_name, None)
|
||||
}
|
||||
|
||||
/// Constructor for file deletion.
|
||||
pub fn new_delete_file(file_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
|
||||
Self::new(FilestoreActionCode::DeleteFile, file_name, None)
|
||||
}
|
||||
|
||||
/// Constructor for file renaming.
|
||||
pub fn new_rename_file(
|
||||
source_name: Lv<'first_name>,
|
||||
target_name: Lv<'second_name>,
|
||||
@@ -566,18 +617,22 @@ impl<'first_name, 'second_name> FilestoreRequestTlv<'first_name, 'second_name> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructor for directory creation.
|
||||
pub fn new_create_directory(dir_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
|
||||
Self::new(FilestoreActionCode::CreateDirectory, dir_name, None)
|
||||
}
|
||||
|
||||
/// Constructor for directory removal.
|
||||
pub fn new_remove_directory(dir_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
|
||||
Self::new(FilestoreActionCode::RemoveDirectory, dir_name, None)
|
||||
}
|
||||
|
||||
/// Constructor for file denial.
|
||||
pub fn new_deny_file(file_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
|
||||
Self::new(FilestoreActionCode::DenyFile, file_name, None)
|
||||
}
|
||||
|
||||
/// Constructor for directory denial.
|
||||
pub fn new_deny_directory(dir_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
|
||||
Self::new(FilestoreActionCode::DenyDirectory, dir_name, None)
|
||||
}
|
||||
@@ -611,31 +666,37 @@ impl<'first_name, 'second_name> FilestoreRequestTlv<'first_name, 'second_name> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Action code.
|
||||
#[inline]
|
||||
pub fn action_code(&self) -> FilestoreActionCode {
|
||||
self.base.action_code
|
||||
}
|
||||
|
||||
/// First name as [Lv].
|
||||
#[inline]
|
||||
pub fn first_name(&self) -> Lv<'first_name> {
|
||||
self.base.first_name
|
||||
}
|
||||
|
||||
/// First name as optional [Lv].
|
||||
#[inline]
|
||||
pub fn second_name(&self) -> Option<Lv<'second_name>> {
|
||||
self.base.second_name
|
||||
}
|
||||
|
||||
/// Length of the value field.
|
||||
#[inline]
|
||||
pub fn len_value(&self) -> usize {
|
||||
self.base.base_len_value()
|
||||
}
|
||||
|
||||
/// Full TLV length.
|
||||
#[inline]
|
||||
pub fn len_full(&self) -> usize {
|
||||
2 + self.len_value()
|
||||
}
|
||||
|
||||
/// Construct from a raw bytestream.
|
||||
pub fn from_bytes<'longest: 'first_name + 'second_name>(
|
||||
buf: &'longest [u8],
|
||||
) -> Result<Self, TlvLvError> {
|
||||
@@ -720,6 +781,7 @@ impl GenericTlv for FilestoreRequestTlv<'_, '_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Filestore response TLV.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -751,6 +813,8 @@ impl<'first_name, 'second_name, 'fs_msg> FilestoreResponseTlv<'first_name, 'seco
|
||||
Lv::new_empty(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Generic constructor.
|
||||
pub fn new(
|
||||
action_code: FilestoreActionCode,
|
||||
status_code: u8,
|
||||
@@ -779,6 +843,7 @@ impl<'first_name, 'second_name, 'fs_msg> FilestoreResponseTlv<'first_name, 'seco
|
||||
})
|
||||
}
|
||||
|
||||
/// Check whether this response has a second filename.
|
||||
pub fn has_second_filename(action_code: FilestoreActionCode) -> bool {
|
||||
if action_code == FilestoreActionCode::RenameFile
|
||||
|| action_code == FilestoreActionCode::AppendFile
|
||||
@@ -789,36 +854,43 @@ impl<'first_name, 'second_name, 'fs_msg> FilestoreResponseTlv<'first_name, 'seco
|
||||
false
|
||||
}
|
||||
|
||||
/// Action code.
|
||||
#[inline]
|
||||
pub fn action_code(&self) -> FilestoreActionCode {
|
||||
self.base.action_code
|
||||
}
|
||||
|
||||
/// Status code.
|
||||
#[inline]
|
||||
pub fn status_code(&self) -> u8 {
|
||||
self.status_code
|
||||
}
|
||||
|
||||
/// First name as [Lv].
|
||||
#[inline]
|
||||
pub fn first_name(&self) -> Lv<'first_name> {
|
||||
self.base.first_name
|
||||
}
|
||||
|
||||
/// Optional second name as [Lv].
|
||||
#[inline]
|
||||
pub fn second_name(&self) -> Option<Lv<'second_name>> {
|
||||
self.base.second_name
|
||||
}
|
||||
|
||||
/// Length of the value field.
|
||||
#[inline]
|
||||
pub fn len_value(&self) -> usize {
|
||||
self.base.base_len_value() + self.filestore_message.len_full()
|
||||
}
|
||||
|
||||
/// Full length of the TLV.
|
||||
#[inline]
|
||||
pub fn len_full(&self) -> usize {
|
||||
2 + self.len_value()
|
||||
}
|
||||
|
||||
/// Construct from a raw bytestream.
|
||||
pub fn from_bytes<'buf: 'first_name + 'second_name + 'fs_msg>(
|
||||
buf: &'buf [u8],
|
||||
) -> Result<Self, TlvLvError> {
|
||||
|
||||
@@ -8,8 +8,10 @@ use crate::{
|
||||
};
|
||||
use delegate::delegate;
|
||||
|
||||
/// Message To User TLV structure.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub struct MsgToUserTlv<'data> {
|
||||
/// Wrapped generic TLV structure.
|
||||
pub tlv: Tlv<'data>,
|
||||
}
|
||||
|
||||
@@ -23,7 +25,9 @@ impl<'data> MsgToUserTlv<'data> {
|
||||
|
||||
delegate! {
|
||||
to self.tlv {
|
||||
/// Value field of the TLV.
|
||||
pub fn value(&self) -> &[u8];
|
||||
|
||||
/// Helper method to retrieve the length of the value. Simply calls the [slice::len] method of
|
||||
/// [Self::value]
|
||||
pub fn len_value(&self) -> usize;
|
||||
@@ -37,14 +41,16 @@ impl<'data> MsgToUserTlv<'data> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is this a standard TLV?
|
||||
#[inline]
|
||||
pub fn is_standard_tlv(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// TLV type field.
|
||||
#[inline]
|
||||
pub fn tlv_type(&self) -> Option<TlvType> {
|
||||
Some(TlvType::MsgToUser)
|
||||
pub fn tlv_type(&self) -> TlvType {
|
||||
TlvType::MsgToUser
|
||||
}
|
||||
|
||||
/// Check whether this message is a reserved CFDP message like a Proxy Operation Message.
|
||||
@@ -85,11 +91,13 @@ impl<'data> MsgToUserTlv<'data> {
|
||||
Ok(msg_to_user)
|
||||
}
|
||||
|
||||
/// Convert to a generic [Tlv].
|
||||
#[inline]
|
||||
pub fn to_tlv(&self) -> Tlv<'data> {
|
||||
self.tlv
|
||||
}
|
||||
|
||||
/// Convert to an [TlvOwned].
|
||||
#[cfg(feature = "alloc")]
|
||||
pub fn to_owned(&self) -> TlvOwned {
|
||||
self.tlv.to_owned()
|
||||
@@ -102,6 +110,7 @@ impl<'data> MsgToUserTlv<'data> {
|
||||
|
||||
delegate!(
|
||||
to self.tlv {
|
||||
/// Write the TLV to a byte buffer.
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;
|
||||
}
|
||||
);
|
||||
@@ -142,7 +151,7 @@ mod tests {
|
||||
assert!(msg_to_user.is_ok());
|
||||
let msg_to_user = msg_to_user.unwrap();
|
||||
assert!(msg_to_user.is_standard_tlv());
|
||||
assert_eq!(msg_to_user.tlv_type().unwrap(), TlvType::MsgToUser);
|
||||
assert_eq!(msg_to_user.tlv_type(), TlvType::MsgToUser);
|
||||
assert_eq!(
|
||||
msg_to_user.tlv_type_field(),
|
||||
TlvTypeField::Standard(TlvType::MsgToUser)
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
//! # CRC checksum support.
|
||||
//!
|
||||
//! Thin wrapper around the [crc] crate.
|
||||
|
||||
/// CRC algorithm used by the PUS standard, the CCSDS TC standard and the CFDP standard, using
|
||||
/// a [crc::NoTable] as the CRC implementation.
|
||||
pub const CRC_CCITT_FALSE_NO_TABLE: crc::Crc<u16, crc::NoTable> =
|
||||
|
||||
@@ -3,17 +3,26 @@ use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Event service subtype ID.
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[repr(u8)]
|
||||
pub enum Subservice {
|
||||
pub enum MessageSubtypeId {
|
||||
/// Telemetry - Info report.
|
||||
TmInfoReport = 1,
|
||||
/// Telemetry - Low severity report.
|
||||
TmLowSeverityReport = 2,
|
||||
/// Telemetry - Medium severity report.
|
||||
TmMediumSeverityReport = 3,
|
||||
/// Telemetry - High severity report.
|
||||
TmHighSeverityReport = 4,
|
||||
/// Telecommand - Enable event generation.
|
||||
TcEnableEventGeneration = 5,
|
||||
/// Telecommand - Disable event generation.
|
||||
TcDisableEventGeneration = 6,
|
||||
/// Telecommand - Report disabled list.
|
||||
TcReportDisabledList = 7,
|
||||
/// Telemetry - Disabled events report.
|
||||
TmDisabledEventsReport = 8,
|
||||
}
|
||||
|
||||
@@ -23,19 +32,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_conv_into_u8() {
|
||||
let subservice: u8 = Subservice::TmLowSeverityReport.into();
|
||||
let subservice: u8 = MessageSubtypeId::TmLowSeverityReport.into();
|
||||
assert_eq!(subservice, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_conv_from_u8() {
|
||||
let subservice: Subservice = 2.try_into().unwrap();
|
||||
assert_eq!(subservice, Subservice::TmLowSeverityReport);
|
||||
let subservice: MessageSubtypeId = 2.try_into().unwrap();
|
||||
assert_eq!(subservice, MessageSubtypeId::TmLowSeverityReport);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_conv_fails() {
|
||||
let conversion = Subservice::try_from(9);
|
||||
let conversion = MessageSubtypeId::try_from(9);
|
||||
assert!(conversion.is_err());
|
||||
let err = conversion.unwrap_err();
|
||||
assert_eq!(err.number, 9);
|
||||
|
||||
@@ -3,31 +3,49 @@ use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Housekeeping service subtype ID.
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum Subservice {
|
||||
pub enum MessageSubtypeId {
|
||||
// Regular HK
|
||||
/// Telecommand - Create Housekeeping Report Structure.
|
||||
TcCreateHkReportStructure = 1,
|
||||
/// Telecommand - Delete HK report structures.
|
||||
TcDeleteHkReportStructures = 3,
|
||||
/// Telecommand - Enable HK generation.
|
||||
TcEnableHkGeneration = 5,
|
||||
/// Telecommand - Disable HK generation.
|
||||
TcDisableHkGeneration = 6,
|
||||
/// Telecommand - Report HK report structures.
|
||||
TcReportHkReportStructures = 9,
|
||||
/// Telemetry - HK report.
|
||||
TmHkPacket = 25,
|
||||
/// Telecommand - Generate one-shot report.
|
||||
TcGenerateOneShotHk = 27,
|
||||
/// Telecommand - Modify collection interval.
|
||||
TcModifyHkCollectionInterval = 31,
|
||||
|
||||
// Diagnostics HK
|
||||
/// Telecommand - Create diagnostics report structures.
|
||||
TcCreateDiagReportStructure = 2,
|
||||
/// Telecommand - Delete diagnostics report structures.
|
||||
TcDeleteDiagReportStructures = 4,
|
||||
/// Telecommand - Enable diagnostics generation.
|
||||
TcEnableDiagGeneration = 7,
|
||||
/// Telecommand - Disable diagnostics generation.
|
||||
TcDisableDiagGeneration = 8,
|
||||
/// Telemetry - HK structures report.
|
||||
TmHkStructuresReport = 10,
|
||||
/// Telecommand - Report diagnostics report structures.
|
||||
TcReportDiagReportStructures = 11,
|
||||
/// Telemetry - Diagnostics report structures.
|
||||
TmDiagStructuresReport = 12,
|
||||
/// Telemetry - Diagnostics packet.
|
||||
TmDiagPacket = 26,
|
||||
/// Telecommand - Generate one-shot diagnostics report.
|
||||
TcGenerateOneShotDiag = 28,
|
||||
/// Telecommand - Modify diagnostics interval report.
|
||||
TcModifyDiagCollectionInterval = 32,
|
||||
}
|
||||
|
||||
@@ -37,25 +55,26 @@ mod tests {
|
||||
#[test]
|
||||
fn test_try_from_u8() {
|
||||
let hk_report_subservice_raw = 25;
|
||||
let hk_report: Subservice = Subservice::try_from(hk_report_subservice_raw).unwrap();
|
||||
assert_eq!(hk_report, Subservice::TmHkPacket);
|
||||
let hk_report: MessageSubtypeId =
|
||||
MessageSubtypeId::try_from(hk_report_subservice_raw).unwrap();
|
||||
assert_eq!(hk_report, MessageSubtypeId::TmHkPacket);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_into_u8() {
|
||||
let hk_report_raw: u8 = Subservice::TmHkPacket.into();
|
||||
let hk_report_raw: u8 = MessageSubtypeId::TmHkPacket.into();
|
||||
assert_eq!(hk_report_raw, 25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_partial_eq() {
|
||||
let hk_report_raw = Subservice::TmHkPacket;
|
||||
assert_ne!(hk_report_raw, Subservice::TcGenerateOneShotHk);
|
||||
assert_eq!(hk_report_raw, Subservice::TmHkPacket);
|
||||
let hk_report_raw = MessageSubtypeId::TmHkPacket;
|
||||
assert_ne!(hk_report_raw, MessageSubtypeId::TcGenerateOneShotHk);
|
||||
assert_eq!(hk_report_raw, MessageSubtypeId::TmHkPacket);
|
||||
}
|
||||
#[test]
|
||||
fn test_copy_clone() {
|
||||
let hk_report = Subservice::TmHkPacket;
|
||||
let hk_report = MessageSubtypeId::TmHkPacket;
|
||||
let hk_report_copy = hk_report;
|
||||
assert_eq!(hk_report, hk_report_copy);
|
||||
}
|
||||
|
||||
160
src/ecss/mod.rs
160
src/ecss/mod.rs
@@ -25,53 +25,55 @@ pub mod tm;
|
||||
pub mod tm_pus_a;
|
||||
pub mod verification;
|
||||
|
||||
/// Type alias for the CRC16 type.
|
||||
pub type CrcType = u16;
|
||||
|
||||
/// Standard PUS service IDs.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
#[non_exhaustive]
|
||||
pub enum PusServiceId {
|
||||
/// Service 1
|
||||
/// Service 1 Verification
|
||||
Verification = 1,
|
||||
/// Service 2
|
||||
/// Service 2 Device Access
|
||||
DeviceAccess = 2,
|
||||
/// Service 3
|
||||
/// Service 3 Housekeeping
|
||||
Housekeeping = 3,
|
||||
/// Service 4
|
||||
/// Service 4 Parameter Statistics
|
||||
ParameterStatistics = 4,
|
||||
/// Service 5
|
||||
/// Service 5 Event
|
||||
Event = 5,
|
||||
/// Service 6
|
||||
/// Service 6 Memory Management
|
||||
MemoryManagement = 6,
|
||||
/// Service 8
|
||||
/// Service 8 Action
|
||||
Action = 8,
|
||||
/// Service 9
|
||||
/// Service 9 Time Management
|
||||
TimeManagement = 9,
|
||||
/// Service 11
|
||||
/// Service 11 Scheduling
|
||||
Scheduling = 11,
|
||||
/// Service 12
|
||||
/// Service 12 On-Board Monitoring
|
||||
OnBoardMonitoring = 12,
|
||||
/// Service 13
|
||||
/// Service 13 Large Packet Transfer
|
||||
LargePacketTransfer = 13,
|
||||
/// Service 14
|
||||
/// Service 14 Real-Time Forwarding Control
|
||||
RealTimeForwardingControl = 14,
|
||||
/// Service 15
|
||||
/// Service 15 Storage And Retrival
|
||||
StorageAndRetrival = 15,
|
||||
/// Service 17
|
||||
/// Service 17 Test
|
||||
Test = 17,
|
||||
/// Service 18
|
||||
/// Service 18 Operations And Procedures
|
||||
OpsAndProcedures = 18,
|
||||
/// Service 19
|
||||
/// Service 19 Event Action
|
||||
EventAction = 19,
|
||||
/// Service 20
|
||||
/// Service 20 Parameter
|
||||
Parameter = 20,
|
||||
/// Service 21
|
||||
/// Service 21 Request Sequencing
|
||||
RequestSequencing = 21,
|
||||
/// Service 22
|
||||
/// Service 22 Position Based Scheduling
|
||||
PositionBasedScheduling = 22,
|
||||
/// Service 23
|
||||
/// Service 23 File Management
|
||||
FileManagement = 23,
|
||||
}
|
||||
|
||||
@@ -83,8 +85,11 @@ pub enum PusServiceId {
|
||||
#[repr(u8)]
|
||||
#[non_exhaustive]
|
||||
pub enum PusVersion {
|
||||
/// ESA PUS
|
||||
EsaPus = 0,
|
||||
/// PUS A
|
||||
PusA = 1,
|
||||
/// PUS C
|
||||
PusC = 2,
|
||||
}
|
||||
|
||||
@@ -107,20 +112,33 @@ impl TryFrom<u4> for PusVersion {
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum PacketTypeCodes {
|
||||
/// Boolean.
|
||||
Boolean = 1,
|
||||
/// Enumerated.
|
||||
Enumerated = 2,
|
||||
/// Unsigned Integer.
|
||||
UnsignedInt = 3,
|
||||
/// Signed Integer.
|
||||
SignedInt = 4,
|
||||
/// Real (floating point).
|
||||
Real = 5,
|
||||
/// Bit string.
|
||||
BitString = 6,
|
||||
/// Octet (byte) string.
|
||||
OctetString = 7,
|
||||
/// Character string.
|
||||
CharString = 8,
|
||||
/// Absolute time.
|
||||
AbsoluteTime = 9,
|
||||
/// Relative time.
|
||||
RelativeTime = 10,
|
||||
/// Deduced.
|
||||
Deduced = 11,
|
||||
/// Packet.
|
||||
Packet = 12,
|
||||
}
|
||||
|
||||
/// Type alias for the ECSS Packet Type Codes (PTC)s.
|
||||
pub type Ptc = PacketTypeCodes;
|
||||
|
||||
/// ECSS Packet Field Codes (PFC)s for the unsigned [Ptc].
|
||||
@@ -129,15 +147,25 @@ pub type Ptc = PacketTypeCodes;
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum PfcUnsigned {
|
||||
/// 1 byte.
|
||||
OneByte = 4,
|
||||
/// 12 bits.
|
||||
TwelveBits = 8,
|
||||
/// 2 bytes.
|
||||
TwoBytes = 12,
|
||||
/// 3 bytes.
|
||||
ThreeBytes = 13,
|
||||
/// 4 bytes.
|
||||
FourBytes = 14,
|
||||
/// 6 bytes.
|
||||
SixBytes = 15,
|
||||
/// 8 bytes.
|
||||
EightBytes = 16,
|
||||
/// 1 bit.
|
||||
OneBit = 17,
|
||||
/// 2 bits.
|
||||
TwoBits = 18,
|
||||
/// 3 bits.
|
||||
ThreeBits = 19,
|
||||
}
|
||||
|
||||
@@ -157,12 +185,15 @@ pub enum PfcReal {
|
||||
DoubleMilStd = 4,
|
||||
}
|
||||
|
||||
/// Generic PUS error.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum PusError {
|
||||
/// PUS version is not supported.
|
||||
#[error("PUS version {0:?} not supported")]
|
||||
VersionNotSupported(u4),
|
||||
/// Checksum failure.
|
||||
#[error("checksum verification for crc16 {0:#06x} failed")]
|
||||
ChecksumFailure(u16),
|
||||
/// CRC16 needs to be calculated first
|
||||
@@ -172,15 +203,54 @@ pub enum PusError {
|
||||
ByteConversion(#[from] ByteConversionError),
|
||||
}
|
||||
|
||||
/// Message type ID field.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct MessageTypeId {
|
||||
/// Service type ID.
|
||||
pub type_id: u8,
|
||||
/// Subtype ID.
|
||||
pub subtype_id: u8,
|
||||
}
|
||||
|
||||
impl MessageTypeId {
|
||||
/// Generic constructor.
|
||||
pub const fn new(type_id: u8, subtype_id: u8) -> Self {
|
||||
Self {
|
||||
type_id,
|
||||
subtype_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generic trait to describe common attributes for both PUS Telecommands (TC) and PUS Telemetry
|
||||
/// (TM) packets. All PUS packets are also a special type of [CcsdsPacket]s.
|
||||
pub trait PusPacket: CcsdsPacket {
|
||||
/// PUS version.
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
|
||||
/// Message type ID.
|
||||
fn message_type_id(&self) -> MessageTypeId;
|
||||
|
||||
/// Service type ID.
|
||||
#[inline]
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.message_type_id().type_id
|
||||
}
|
||||
|
||||
/// Message subtype ID.
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.message_type_id().subtype_id
|
||||
}
|
||||
|
||||
/// User data field.
|
||||
fn user_data(&self) -> &[u8];
|
||||
|
||||
/// CRC-16-CCITT checksum.
|
||||
fn checksum(&self) -> Option<u16>;
|
||||
|
||||
/// The presence of the CRC-16-CCITT checksum is optional.
|
||||
fn has_checksum(&self) -> bool {
|
||||
self.checksum().is_some()
|
||||
@@ -226,6 +296,7 @@ pub(crate) fn user_data_from_raw(
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify the CRC16 of a raw packet and return a [PusError] on failure.
|
||||
pub fn verify_crc16_ccitt_false_from_raw_to_pus_error(
|
||||
raw_data: &[u8],
|
||||
crc16: u16,
|
||||
@@ -235,6 +306,8 @@ pub fn verify_crc16_ccitt_false_from_raw_to_pus_error(
|
||||
.ok_or(PusError::ChecksumFailure(crc16))
|
||||
}
|
||||
|
||||
/// Verify the CRC16 of a raw packet using a table-less implementation and return a [PusError] on
|
||||
/// failure.
|
||||
pub fn verify_crc16_ccitt_false_from_raw_to_pus_error_no_table(
|
||||
raw_data: &[u8],
|
||||
crc16: u16,
|
||||
@@ -267,10 +340,15 @@ pub fn verify_crc16_ccitt_false_from_raw_no_table(raw_data: &[u8]) -> bool {
|
||||
macro_rules! sp_header_impls {
|
||||
() => {
|
||||
delegate!(to self.sp_header {
|
||||
/// Set the CCSDS APID.
|
||||
#[inline]
|
||||
pub fn set_apid(&mut self, apid: u11);
|
||||
|
||||
/// Set the CCSDS sequence count.
|
||||
#[inline]
|
||||
pub fn set_seq_count(&mut self, seq_count: u14);
|
||||
|
||||
/// Set the CCSDS sequence flags.
|
||||
#[inline]
|
||||
pub fn set_seq_flags(&mut self, seq_flag: SequenceFlags);
|
||||
});
|
||||
@@ -289,27 +367,28 @@ pub trait EcssEnumeration: UnsignedEnum {
|
||||
fn pfc(&self) -> u8;
|
||||
}
|
||||
|
||||
/// Extension trait for [EcssEnumeration] which adds common trait bounds.
|
||||
pub trait EcssEnumerationExt: EcssEnumeration + Debug + Copy + Clone + PartialEq + Eq {}
|
||||
|
||||
/// ECSS enumerated type wrapper.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct GenericEcssEnumWrapper<TYPE: Copy + Into<u64>> {
|
||||
field: GenericUnsignedByteField<TYPE>,
|
||||
}
|
||||
pub struct GenericEcssEnumWrapper<TYPE: Copy + Into<u64>>(GenericUnsignedByteField<TYPE>);
|
||||
|
||||
impl<TYPE: Copy + Into<u64>> GenericEcssEnumWrapper<TYPE> {
|
||||
/// Returns [PacketTypeCodes::Enumerated].
|
||||
pub const fn ptc() -> PacketTypeCodes {
|
||||
PacketTypeCodes::Enumerated
|
||||
}
|
||||
|
||||
pub const fn value_typed(&self) -> TYPE {
|
||||
self.field.value_typed()
|
||||
/// Value.
|
||||
pub const fn value(&self) -> TYPE {
|
||||
self.0.value()
|
||||
}
|
||||
|
||||
pub fn new(val: TYPE) -> Self {
|
||||
Self {
|
||||
field: GenericUnsignedByteField::new(val),
|
||||
}
|
||||
/// Generic constructor.
|
||||
pub const fn new(val: TYPE) -> Self {
|
||||
Self(GenericUnsignedByteField::new(val))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,11 +398,11 @@ impl<TYPE: Copy + ToBeBytes + Into<u64>> UnsignedEnum for GenericEcssEnumWrapper
|
||||
}
|
||||
|
||||
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
self.field.write_to_be_bytes(buf)
|
||||
self.0.write_to_be_bytes(buf)
|
||||
}
|
||||
|
||||
fn value(&self) -> u64 {
|
||||
self.field.value()
|
||||
fn value_raw(&self) -> u64 {
|
||||
self.0.value().into()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -347,11 +426,12 @@ impl<T: Copy + Into<u64>> From<T> for GenericEcssEnumWrapper<T> {
|
||||
macro_rules! generic_ecss_enum_typedefs_and_from_impls {
|
||||
($($ty:ty => $Enum:ident),*) => {
|
||||
$(
|
||||
/// Type alias for ECSS enumeration wrapper around `$ty`
|
||||
pub type $Enum = GenericEcssEnumWrapper<$ty>;
|
||||
|
||||
impl From<$Enum> for $ty {
|
||||
fn from(value: $Enum) -> Self {
|
||||
value.value_typed()
|
||||
value.value()
|
||||
}
|
||||
}
|
||||
)*
|
||||
@@ -412,6 +492,7 @@ pub trait WritablePusPacket {
|
||||
Ok(curr_idx)
|
||||
}
|
||||
|
||||
/// Converts the packet into an owned [alloc::vec::Vec].
|
||||
#[cfg(feature = "alloc")]
|
||||
fn to_vec(&self) -> Result<Vec<u8>, PusError> {
|
||||
// This is the correct way to do this. See
|
||||
@@ -423,6 +504,7 @@ pub trait WritablePusPacket {
|
||||
}
|
||||
}
|
||||
|
||||
/// PUS packet creator configuration.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -465,7 +547,7 @@ mod tests {
|
||||
.expect("To byte conversion of u8 failed");
|
||||
assert_eq!(buf[1], 1);
|
||||
assert_eq!(my_enum.value(), 1);
|
||||
assert_eq!(my_enum.value_typed(), 1);
|
||||
assert_eq!(my_enum.value(), 1);
|
||||
let enum_as_u8: u8 = my_enum.into();
|
||||
assert_eq!(enum_as_u8, 1);
|
||||
let vec = my_enum.to_vec();
|
||||
@@ -484,7 +566,7 @@ mod tests {
|
||||
assert_eq!(buf[1], 0x1f);
|
||||
assert_eq!(buf[2], 0x2f);
|
||||
assert_eq!(my_enum.value(), 0x1f2f);
|
||||
assert_eq!(my_enum.value_typed(), 0x1f2f);
|
||||
assert_eq!(my_enum.value(), 0x1f2f);
|
||||
let enum_as_raw: u16 = my_enum.into();
|
||||
assert_eq!(enum_as_raw, 0x1f2f);
|
||||
let vec = my_enum.to_vec();
|
||||
@@ -521,7 +603,7 @@ mod tests {
|
||||
assert_eq!(buf[3], 0x3f);
|
||||
assert_eq!(buf[4], 0x4f);
|
||||
assert_eq!(my_enum.value(), 0x1f2f3f4f);
|
||||
assert_eq!(my_enum.value_typed(), 0x1f2f3f4f);
|
||||
assert_eq!(my_enum.value(), 0x1f2f3f4f);
|
||||
let enum_as_raw: u32 = my_enum.into();
|
||||
assert_eq!(enum_as_raw, 0x1f2f3f4f);
|
||||
let vec = my_enum.to_vec();
|
||||
@@ -559,7 +641,7 @@ mod tests {
|
||||
assert_eq!(buf[6], 0x4f);
|
||||
assert_eq!(buf[7], 0x5f);
|
||||
assert_eq!(my_enum.value(), 0x1f2f3f4f5f);
|
||||
assert_eq!(my_enum.value_typed(), 0x1f2f3f4f5f);
|
||||
assert_eq!(my_enum.value(), 0x1f2f3f4f5f);
|
||||
let enum_as_raw: u64 = my_enum.into();
|
||||
assert_eq!(enum_as_raw, 0x1f2f3f4f5f);
|
||||
assert_eq!(u64::from_be_bytes(buf), 0x1f2f3f4f5f);
|
||||
|
||||
@@ -3,46 +3,74 @@ use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Scheduling service subtype ID.
|
||||
#[derive(Debug, PartialEq, Eq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum Subservice {
|
||||
pub enum MessageSubtypeId {
|
||||
// Core subservices
|
||||
/// Telecommand - Enable scheduling.
|
||||
TcEnableScheduling = 1,
|
||||
/// Telecommand - Disable scheduling.
|
||||
TcDisableScheduling = 2,
|
||||
/// Telecommand - Reset scheduling.
|
||||
TcResetScheduling = 3,
|
||||
/// Telecommand - Insert activity.
|
||||
TcInsertActivity = 4,
|
||||
/// Telecommand - Delete activity by request ID.
|
||||
TcDeleteActivityByRequestId = 5,
|
||||
/// Telecommand - Delete activity by filter.
|
||||
TcDeleteActivitiesByFilter = 6,
|
||||
|
||||
// Time shift subservices
|
||||
/// Telecommand - Time shift activity by request ID.
|
||||
TcTimeShiftActivityWithRequestId = 7,
|
||||
/// Telecommand - Time shift activity by filter.
|
||||
TcTimeShiftActivitiesByFilter = 8,
|
||||
/// Telecommand - Time shift all.
|
||||
TcTimeShiftAll = 15,
|
||||
|
||||
// Reporting subservices
|
||||
/// Telecommand - Detail report by request ID.
|
||||
TcDetailReportByRequestId = 9,
|
||||
/// Telemetry - Detail report.
|
||||
TmDetailReport = 10,
|
||||
/// Telecommand - Detail report by filter.
|
||||
TcDetailReportByFilter = 11,
|
||||
/// Telecommand - Summary report by request ID.
|
||||
TcSummaryReportByRequestId = 12,
|
||||
/// Telemetry - Summary report.
|
||||
TmSummaryReport = 13,
|
||||
/// Telecommand - Summary report by filter.
|
||||
TcSummaryReportByFilter = 14,
|
||||
/// Telecommand - Detail report all.
|
||||
TcDetailReportAll = 16,
|
||||
/// Telecommand - Summary report all.
|
||||
TcSummaryReportAll = 17,
|
||||
|
||||
// Subschedule subservices
|
||||
/// Telecommand - Report subschedule status.
|
||||
TcReportSubscheduleStatus = 18,
|
||||
/// Telemetry - Subschedule status report.
|
||||
TmReportSubscheduleStatus = 19,
|
||||
/// Telecommand - Enable subschedule.
|
||||
TcEnableSubschedule = 20,
|
||||
/// Telecommand - Disable subschedule.
|
||||
TcDisableSubschedule = 21,
|
||||
|
||||
// Group subservices
|
||||
/// Telecommand - Create schedule group.
|
||||
TcCreateScheduleGroup = 22,
|
||||
/// Telecommand - Delete schedule group.
|
||||
TcDeleteScheduleGroup = 23,
|
||||
/// Telecommand - Enable schedule group.
|
||||
TcEnableScheduleGroup = 24,
|
||||
/// Telecommand - Disable schedule group.
|
||||
TcDisableScheduleGroup = 25,
|
||||
/// Telecommand - Report all group status.
|
||||
TcReportAllGroupsStatus = 26,
|
||||
/// Telemetry - All group status report.
|
||||
TmReportAllGroupsStatus = 27,
|
||||
}
|
||||
|
||||
@@ -51,7 +79,9 @@ pub enum Subservice {
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum SchedStatus {
|
||||
/// Scheduling disabled.
|
||||
Disabled = 0,
|
||||
/// Scheduling enabled.
|
||||
Enabled = 1,
|
||||
}
|
||||
|
||||
@@ -71,9 +101,13 @@ impl From<bool> for SchedStatus {
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum TimeWindowType {
|
||||
/// Select all.
|
||||
SelectAll = 0,
|
||||
/// From time tag to time tag.
|
||||
TimeTagToTimeTag = 1,
|
||||
/// Starting from a time tag.
|
||||
FromTimeTag = 2,
|
||||
/// Until a time tag.
|
||||
ToTimeTag = 3,
|
||||
}
|
||||
|
||||
@@ -99,20 +133,20 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_conv_into_u8() {
|
||||
let subservice: u8 = Subservice::TcCreateScheduleGroup.into();
|
||||
let subservice: u8 = MessageSubtypeId::TcCreateScheduleGroup.into();
|
||||
assert_eq!(subservice, 22);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_conv_from_u8() {
|
||||
let subservice: Subservice = 22u8.try_into().unwrap();
|
||||
assert_eq!(subservice, Subservice::TcCreateScheduleGroup);
|
||||
let subservice: MessageSubtypeId = 22u8.try_into().unwrap();
|
||||
assert_eq!(subservice, MessageSubtypeId::TcCreateScheduleGroup);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "serde")]
|
||||
fn test_serde_subservice_id() {
|
||||
generic_serde_test(Subservice::TcEnableScheduling);
|
||||
generic_serde_test(MessageSubtypeId::TcEnableScheduling);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
239
src/ecss/tc.rs
239
src/ecss/tc.rs
@@ -5,18 +5,18 @@
|
||||
//!
|
||||
//! ```rust
|
||||
//! use spacepackets::SpHeader;
|
||||
//! use spacepackets::ecss::tc::{PusTcCreator, PusTcReader, PusTcSecondaryHeader, CreatorConfig};
|
||||
//! use spacepackets::ecss::tc::{MessageTypeId, PusTcCreator, PusTcReader, PusTcSecondaryHeader, CreatorConfig};
|
||||
//! use arbitrary_int::u11;
|
||||
//!
|
||||
//! // Create a ping telecommand with no user application data
|
||||
//! let pus_tc = PusTcCreator::new_no_app_data(
|
||||
//! SpHeader::new_from_apid(u11::new(0x02)),
|
||||
//! PusTcSecondaryHeader::new_simple(17, 1),
|
||||
//! PusTcSecondaryHeader::new_simple(MessageTypeId::new(17, 1)),
|
||||
//! CreatorConfig::default()
|
||||
//! );
|
||||
//! println!("{:?}", pus_tc);
|
||||
//! assert_eq!(pus_tc.service(), 17);
|
||||
//! assert_eq!(pus_tc.subservice(), 1);
|
||||
//! assert_eq!(pus_tc.service_type_id(), 17);
|
||||
//! assert_eq!(pus_tc.message_subtype_id(), 1);
|
||||
//! assert_eq!(pus_tc.apid().value(), 0x02);
|
||||
//!
|
||||
//! // Serialize TC into a raw buffer
|
||||
@@ -29,25 +29,25 @@
|
||||
//!
|
||||
//! // Deserialize from the raw byte representation
|
||||
//! let pus_tc_deserialized = PusTcReader::new(&test_buf).expect("Deserialization failed");
|
||||
//! assert_eq!(pus_tc.service(), 17);
|
||||
//! assert_eq!(pus_tc.subservice(), 1);
|
||||
//! assert_eq!(pus_tc.service_type_id(), 17);
|
||||
//! assert_eq!(pus_tc.message_subtype_id(), 1);
|
||||
//! assert_eq!(pus_tc.apid().value(), 0x02);
|
||||
//!
|
||||
//! // Alternative builder API
|
||||
//! let pus_tc_by_builder = PusTcCreator::builder()
|
||||
//! .with_service(17)
|
||||
//! .with_subservice(1)
|
||||
//! .with_service_type_id(17)
|
||||
//! .with_message_subtype_id(1)
|
||||
//! .with_apid(u11::new(0x02))
|
||||
//! .build();
|
||||
//! assert_eq!(pus_tc_by_builder, pus_tc);
|
||||
//! ```
|
||||
use crate::crc::{CRC_CCITT_FALSE, CRC_CCITT_FALSE_NO_TABLE};
|
||||
pub use crate::ecss::CreatorConfig;
|
||||
use crate::ecss::{
|
||||
crc_from_raw_data, sp_header_impls, user_data_from_raw,
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error, PusError, PusPacket, PusVersion,
|
||||
WritablePusPacket,
|
||||
};
|
||||
pub use crate::ecss::{CreatorConfig, MessageTypeId};
|
||||
use crate::{ByteConversionError, CcsdsPacket, PacketType, SequenceFlags, CCSDS_HEADER_LEN};
|
||||
use crate::{PacketId, PacketSequenceControl, SpHeader};
|
||||
use arbitrary_int::{u11, u14, u3, u4};
|
||||
@@ -68,26 +68,33 @@ use super::verify_crc16_ccitt_false_from_raw_to_pus_error_no_table;
|
||||
|
||||
/// PUS C secondary header length is fixed
|
||||
pub const PUC_TC_SECONDARY_HEADER_LEN: usize = size_of::<zc::PusTcSecondaryHeader>();
|
||||
/// Minimum PUS C secondary header length without application data.
|
||||
pub const PUS_TC_MIN_LEN_WITHOUT_APP_DATA: usize = CCSDS_HEADER_LEN + PUC_TC_SECONDARY_HEADER_LEN;
|
||||
const PUS_VERSION: PusVersion = PusVersion::PusC;
|
||||
|
||||
/// Marker trait for PUS telecommand structures.
|
||||
pub trait IsPusTelecommand {}
|
||||
|
||||
/// Acknowledgement flags for PUS telecommands.
|
||||
#[bitbybit::bitfield(u4, default = 0b0000, debug, defmt_bitfields(feature = "defmt"))]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub struct AckFlags {
|
||||
/// Acceptance must be acknowledged.
|
||||
#[bit(3, rw)]
|
||||
acceptance: bool,
|
||||
/// Start must be acknowledged.
|
||||
#[bit(2, rw)]
|
||||
start: bool,
|
||||
/// Progress must be acknowledged.
|
||||
#[bit(1, rw)]
|
||||
progress: bool,
|
||||
/// Completion must be acknowledged.
|
||||
#[bit(0, rw)]
|
||||
completion: bool,
|
||||
}
|
||||
|
||||
/// Constant to acknowledge all TC handling phases.
|
||||
pub const ACK_ALL: AckFlags = AckFlags::builder()
|
||||
.with_acceptance(true)
|
||||
.with_start(true)
|
||||
@@ -96,30 +103,49 @@ pub const ACK_ALL: AckFlags = AckFlags::builder()
|
||||
.build();
|
||||
|
||||
impl AckFlags {
|
||||
/// Constant to acknowledge all TC handling phases.
|
||||
pub const ALL: Self = ACK_ALL;
|
||||
}
|
||||
|
||||
/// Generic trait for PUS TC secondary header access.
|
||||
pub trait GenericPusTcSecondaryHeader {
|
||||
/// PUS version.
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
/// Acknowledgement flags.
|
||||
fn ack_flags(&self) -> AckFlags;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
/// Message type ID.
|
||||
fn message_type_id(&self) -> MessageTypeId;
|
||||
/// Source ID.
|
||||
fn source_id(&self) -> u16;
|
||||
|
||||
/// Service type ID.
|
||||
#[inline]
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.message_type_id().type_id
|
||||
}
|
||||
|
||||
/// Message subtype ID.
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.message_type_id().subtype_id
|
||||
}
|
||||
}
|
||||
|
||||
/// [zerocopy] support.
|
||||
pub mod zc {
|
||||
use crate::ecss::tc::{AckFlags, GenericPusTcSecondaryHeader};
|
||||
use crate::ecss::{PusError, PusVersion};
|
||||
use crate::ecss::{MessageTypeId, PusError, PusVersion};
|
||||
use arbitrary_int::traits::Integer;
|
||||
use arbitrary_int::u4;
|
||||
use zerocopy::{FromBytes, Immutable, IntoBytes, NetworkEndian, Unaligned, U16};
|
||||
|
||||
/// PUS TC secondary header.
|
||||
#[derive(FromBytes, IntoBytes, Immutable, Unaligned)]
|
||||
#[repr(C)]
|
||||
pub struct PusTcSecondaryHeader {
|
||||
version_ack: u8,
|
||||
service: u8,
|
||||
subservice: u8,
|
||||
service_type_id: u8,
|
||||
message_subtype_id: u8,
|
||||
source_id: U16<NetworkEndian>,
|
||||
}
|
||||
|
||||
@@ -131,8 +157,8 @@ pub mod zc {
|
||||
}
|
||||
Ok(PusTcSecondaryHeader {
|
||||
version_ack: ((value.version as u8) << 4) | value.ack_flags.raw_value().as_u8(),
|
||||
service: value.service,
|
||||
subservice: value.subservice,
|
||||
service_type_id: value.service_type_id(),
|
||||
message_subtype_id: value.message_subtype_id(),
|
||||
source_id: U16::from(value.source_id),
|
||||
})
|
||||
}
|
||||
@@ -150,13 +176,22 @@ pub mod zc {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service(&self) -> u8 {
|
||||
self.service
|
||||
/// Message type ID.
|
||||
fn message_type_id(&self) -> MessageTypeId {
|
||||
MessageTypeId {
|
||||
type_id: self.service_type_id,
|
||||
subtype_id: self.message_subtype_id,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8 {
|
||||
self.subservice
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.service_type_id
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.message_subtype_id
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -166,14 +201,18 @@ pub mod zc {
|
||||
}
|
||||
}
|
||||
|
||||
/// PUS C secondary header for telecommands.
|
||||
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PusTcSecondaryHeader {
|
||||
pub service: u8,
|
||||
pub subservice: u8,
|
||||
/// Message type ID.
|
||||
pub message_type_id: MessageTypeId,
|
||||
/// Source ID.
|
||||
pub source_id: u16,
|
||||
/// Acknowledgement flags.
|
||||
pub ack_flags: AckFlags,
|
||||
/// PUS version.
|
||||
pub version: PusVersion,
|
||||
}
|
||||
|
||||
@@ -189,13 +228,8 @@ impl GenericPusTcSecondaryHeader for PusTcSecondaryHeader {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service(&self) -> u8 {
|
||||
self.service
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8 {
|
||||
self.subservice
|
||||
fn message_type_id(&self) -> MessageTypeId {
|
||||
self.message_type_id
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -209,8 +243,7 @@ impl TryFrom<zc::PusTcSecondaryHeader> for PusTcSecondaryHeader {
|
||||
|
||||
fn try_from(value: zc::PusTcSecondaryHeader) -> Result<Self, Self::Error> {
|
||||
Ok(PusTcSecondaryHeader {
|
||||
service: value.service(),
|
||||
subservice: value.subservice(),
|
||||
message_type_id: value.message_type_id(),
|
||||
source_id: value.source_id(),
|
||||
ack_flags: value.ack_flags(),
|
||||
version: PUS_VERSION,
|
||||
@@ -219,24 +252,25 @@ impl TryFrom<zc::PusTcSecondaryHeader> for PusTcSecondaryHeader {
|
||||
}
|
||||
|
||||
impl PusTcSecondaryHeader {
|
||||
/// Header length constant.
|
||||
pub const HEADER_LEN: usize = PUC_TC_SECONDARY_HEADER_LEN;
|
||||
|
||||
/// Simple constructor which only requires the [MessageTypeId].
|
||||
#[inline]
|
||||
pub fn new_simple(service: u8, subservice: u8) -> Self {
|
||||
pub fn new_simple(message_type_id: MessageTypeId) -> Self {
|
||||
PusTcSecondaryHeader {
|
||||
service,
|
||||
subservice,
|
||||
message_type_id,
|
||||
ack_flags: ACK_ALL,
|
||||
source_id: 0,
|
||||
version: PusVersion::PusC,
|
||||
}
|
||||
}
|
||||
|
||||
/// General constructor.
|
||||
#[inline]
|
||||
pub fn new(service: u8, subservice: u8, ack_flags: AckFlags, source_id: u16) -> Self {
|
||||
pub fn new(message_type_id: MessageTypeId, ack_flags: AckFlags, source_id: u16) -> Self {
|
||||
PusTcSecondaryHeader {
|
||||
service,
|
||||
subservice,
|
||||
message_type_id,
|
||||
ack_flags,
|
||||
source_id,
|
||||
version: PusVersion::PusC,
|
||||
@@ -257,6 +291,7 @@ impl PusTcSecondaryHeader {
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PusTcCreator<'app_data> {
|
||||
sp_header: SpHeader,
|
||||
/// Secondary header.
|
||||
pub sec_header: PusTcSecondaryHeader,
|
||||
app_data: &'app_data [u8],
|
||||
has_checksum: bool,
|
||||
@@ -299,19 +334,19 @@ impl<'app_data> PusTcCreator<'app_data> {
|
||||
#[inline]
|
||||
pub fn new_simple(
|
||||
sph: SpHeader,
|
||||
service: u8,
|
||||
subservice: u8,
|
||||
message_type_id: MessageTypeId,
|
||||
app_data: &'app_data [u8],
|
||||
packet_config: CreatorConfig,
|
||||
) -> Self {
|
||||
Self::new(
|
||||
sph,
|
||||
PusTcSecondaryHeader::new(service, subservice, ACK_ALL, 0),
|
||||
PusTcSecondaryHeader::new(message_type_id, ACK_ALL, 0),
|
||||
app_data,
|
||||
packet_config,
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructor for a PUS TC packet without application data.
|
||||
#[inline]
|
||||
pub fn new_no_app_data(
|
||||
sp_header: SpHeader,
|
||||
@@ -321,40 +356,48 @@ impl<'app_data> PusTcCreator<'app_data> {
|
||||
Self::new(sp_header, sec_header, &[], packet_config)
|
||||
}
|
||||
|
||||
/// Get a builder whih allows building [Self] step-by-step.
|
||||
pub fn builder<'a>() -> PusTcBuilder<'a> {
|
||||
PusTcBuilder::default()
|
||||
}
|
||||
|
||||
/// Space packet header.
|
||||
#[inline]
|
||||
pub fn sp_header(&self) -> &SpHeader {
|
||||
&self.sp_header
|
||||
}
|
||||
|
||||
/// Mutable access to the space packet header.
|
||||
#[inline]
|
||||
pub fn sp_header_mut(&mut self) -> &mut SpHeader {
|
||||
&mut self.sp_header
|
||||
}
|
||||
|
||||
/// Service type ID.
|
||||
#[inline]
|
||||
pub fn service(&self) -> u8 {
|
||||
self.sec_header.service
|
||||
pub fn service_type_id(&self) -> u8 {
|
||||
self.sec_header.service_type_id()
|
||||
}
|
||||
|
||||
/// Message subtype ID.
|
||||
#[inline]
|
||||
pub fn subservice(&self) -> u8 {
|
||||
self.sec_header.subservice
|
||||
pub fn message_subtype_id(&self) -> u8 {
|
||||
self.sec_header.message_subtype_id()
|
||||
}
|
||||
|
||||
/// Application Process ID (APID).
|
||||
#[inline]
|
||||
pub fn apid(&self) -> u11 {
|
||||
self.sp_header.packet_id.apid
|
||||
}
|
||||
|
||||
/// Set acknowledgement flags.
|
||||
#[inline]
|
||||
pub fn set_ack_flags(&mut self, ack_flags: AckFlags) {
|
||||
self.sec_header.ack_flags = ack_flags;
|
||||
}
|
||||
|
||||
/// Set the source ID.
|
||||
#[inline]
|
||||
pub fn set_source_id(&mut self, source_id: u16) {
|
||||
self.sec_header.source_id = source_id;
|
||||
@@ -396,11 +439,13 @@ impl<'app_data> PusTcCreator<'app_data> {
|
||||
digest.finalize()
|
||||
}
|
||||
|
||||
/// Current packet has a checksum.
|
||||
#[inline]
|
||||
pub fn has_checksum(&self) -> bool {
|
||||
self.has_checksum
|
||||
}
|
||||
|
||||
/// Append the raw PUS byte representation to a provided vector.
|
||||
#[cfg(feature = "alloc")]
|
||||
pub fn append_to_vec(&self, vec: &mut Vec<u8>) -> usize {
|
||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||
@@ -513,9 +558,11 @@ impl PusPacket for PusTcCreator<'_> {
|
||||
#[inline]
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
fn message_type_id(&self) -> MessageTypeId;
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
fn service_type_id(&self) -> u8;
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8;
|
||||
});
|
||||
|
||||
#[inline]
|
||||
@@ -541,9 +588,11 @@ impl GenericPusTcSecondaryHeader for PusTcCreator<'_> {
|
||||
#[inline]
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
fn message_type_id(&self) -> MessageTypeId;
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
fn service_type_id(&self) -> u8;
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8;
|
||||
#[inline]
|
||||
fn source_id(&self) -> u16;
|
||||
#[inline]
|
||||
@@ -638,6 +687,7 @@ impl<'buf> PusTcCreatorWithReservedAppData<'buf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Length of the full packet written into a buffer.
|
||||
#[inline]
|
||||
pub const fn len_written(&self) -> usize {
|
||||
self.full_len
|
||||
@@ -665,6 +715,7 @@ impl<'buf> PusTcCreatorWithReservedAppData<'buf> {
|
||||
&self.buf[self.app_data_offset..end_index]
|
||||
}
|
||||
|
||||
/// Length of the application data.
|
||||
#[inline]
|
||||
pub fn app_data_len(&self) -> usize {
|
||||
let mut len = self.full_len - self.app_data_offset;
|
||||
@@ -727,6 +778,7 @@ pub struct PusTcBuilder<'a> {
|
||||
}
|
||||
|
||||
impl PusTcBuilder<'_> {
|
||||
/// Constructor.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
sp_header: SpHeader::new(
|
||||
@@ -734,12 +786,13 @@ impl PusTcBuilder<'_> {
|
||||
PacketSequenceControl::new(SequenceFlags::Unsegmented, u14::new(0)),
|
||||
0,
|
||||
),
|
||||
sec_header: PusTcSecondaryHeader::new(0, 0, ACK_ALL, 0),
|
||||
sec_header: PusTcSecondaryHeader::new(MessageTypeId::new(0, 0), ACK_ALL, 0),
|
||||
app_data: &[],
|
||||
has_checksum: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the packet ID.
|
||||
#[inline]
|
||||
pub fn with_packet_id(mut self, mut packet_id: PacketId) -> Self {
|
||||
packet_id.packet_type = PacketType::Tc;
|
||||
@@ -747,48 +800,63 @@ impl PusTcBuilder<'_> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the packet sequence control.
|
||||
#[inline]
|
||||
pub fn with_packet_sequence_control(mut self, psc: PacketSequenceControl) -> Self {
|
||||
self.sp_header.psc = psc;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the sequence count.
|
||||
#[inline]
|
||||
pub fn with_sequence_count(mut self, seq_count: u14) -> Self {
|
||||
self.sp_header.psc.seq_count = seq_count;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the message type ID.
|
||||
#[inline]
|
||||
pub fn with_service(mut self, service: u8) -> Self {
|
||||
self.sec_header.service = service;
|
||||
pub fn with_message_type_id(mut self, message_type: MessageTypeId) -> Self {
|
||||
self.sec_header.message_type_id = message_type;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the service type ID.
|
||||
#[inline]
|
||||
pub fn with_subservice(mut self, service: u8) -> Self {
|
||||
self.sec_header.subservice = service;
|
||||
pub fn with_service_type_id(mut self, service: u8) -> Self {
|
||||
self.sec_header.message_type_id.type_id = service;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the message subtype ID.
|
||||
#[inline]
|
||||
pub fn with_message_subtype_id(mut self, subtype_id: u8) -> Self {
|
||||
self.sec_header.message_type_id.subtype_id = subtype_id;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the source ID.
|
||||
#[inline]
|
||||
pub fn with_source_id(mut self, source_id: u16) -> Self {
|
||||
self.sec_header.source_id = source_id;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the acknowledgmenet flags.
|
||||
#[inline]
|
||||
pub fn with_ack_flags(mut self, ack_flags: AckFlags) -> Self {
|
||||
self.sec_header.ack_flags = ack_flags;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the Application Process ID (APID).
|
||||
#[inline]
|
||||
pub fn with_apid(mut self, apid: u11) -> Self {
|
||||
self.sp_header.packet_id.set_apid(apid);
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable or disable the checksum.
|
||||
#[inline]
|
||||
pub fn with_checksum(mut self, has_checksum: bool) -> Self {
|
||||
self.has_checksum = has_checksum;
|
||||
@@ -803,6 +871,7 @@ impl Default for PusTcBuilder<'_> {
|
||||
}
|
||||
|
||||
impl<'a> PusTcBuilder<'a> {
|
||||
/// Constructor.
|
||||
pub fn build(self) -> PusTcCreator<'a> {
|
||||
PusTcCreator::new(
|
||||
self.sp_header,
|
||||
@@ -815,6 +884,7 @@ impl<'a> PusTcBuilder<'a> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Application data slice.
|
||||
#[inline]
|
||||
pub fn with_app_data(mut self, app_data: &'a [u8]) -> Self {
|
||||
self.app_data = app_data;
|
||||
@@ -923,26 +993,31 @@ impl<'raw_data> PusTcReader<'raw_data> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Application data slice.
|
||||
#[inline]
|
||||
pub fn app_data(&self) -> &[u8] {
|
||||
self.user_data()
|
||||
}
|
||||
|
||||
/// Full raw data slice.
|
||||
#[inline]
|
||||
pub fn raw_data(&self) -> &[u8] {
|
||||
self.raw_data
|
||||
}
|
||||
|
||||
/// Length of the packed data.
|
||||
#[inline]
|
||||
pub fn len_packed(&self) -> usize {
|
||||
self.sp_header.packet_len()
|
||||
}
|
||||
|
||||
/// Space packet header.
|
||||
#[inline]
|
||||
pub fn sp_header(&self) -> &SpHeader {
|
||||
&self.sp_header
|
||||
}
|
||||
|
||||
/// CRC16 checksum if present.
|
||||
#[inline]
|
||||
pub fn crc16(&self) -> Option<u16> {
|
||||
self.crc16
|
||||
@@ -974,9 +1049,11 @@ impl PusPacket for PusTcReader<'_> {
|
||||
#[inline]
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
fn message_type_id(&self) -> MessageTypeId;
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
fn service_type_id(&self) -> u8;
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8;
|
||||
});
|
||||
|
||||
fn has_checksum(&self) -> bool {
|
||||
@@ -999,9 +1076,11 @@ impl GenericPusTcSecondaryHeader for PusTcReader<'_> {
|
||||
#[inline]
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
fn message_type_id(&self) -> MessageTypeId;
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
fn service_type_id(&self) -> u8;
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8;
|
||||
#[inline]
|
||||
fn source_id(&self) -> u16;
|
||||
#[inline]
|
||||
@@ -1042,13 +1121,13 @@ mod tests {
|
||||
|
||||
fn base_ping_tc_full_ctor() -> PusTcCreator<'static> {
|
||||
let sph = SpHeader::new_for_unseg_tc(u11::new(0x02), u14::new(0x34), 0);
|
||||
let tc_header = PusTcSecondaryHeader::new_simple(17, 1);
|
||||
let tc_header = PusTcSecondaryHeader::new_simple(MessageTypeId::new(17, 1));
|
||||
PusTcCreator::new_no_app_data(sph, tc_header, CreatorConfig::default())
|
||||
}
|
||||
|
||||
fn base_ping_tc_full_ctor_no_checksum() -> PusTcCreator<'static> {
|
||||
let sph = SpHeader::new_for_unseg_tc(u11::new(0x02), u14::new(0x34), 0);
|
||||
let tc_header = PusTcSecondaryHeader::new_simple(17, 1);
|
||||
let tc_header = PusTcSecondaryHeader::new_simple(MessageTypeId::new(17, 1));
|
||||
PusTcCreator::new_no_app_data(
|
||||
sph,
|
||||
tc_header,
|
||||
@@ -1061,21 +1140,26 @@ mod tests {
|
||||
|
||||
fn base_ping_tc_simple_ctor() -> PusTcCreator<'static> {
|
||||
let sph = SpHeader::new_for_unseg_tc(u11::new(0x02), u14::new(0x34), 0);
|
||||
PusTcCreator::new_simple(sph, 17, 1, &[], CreatorConfig::default())
|
||||
PusTcCreator::new_simple(
|
||||
sph,
|
||||
MessageTypeId::new(17, 1),
|
||||
&[],
|
||||
CreatorConfig::default(),
|
||||
)
|
||||
}
|
||||
|
||||
fn base_ping_tc_with_builder(alt_api: bool) -> PusTcCreator<'static> {
|
||||
if alt_api {
|
||||
return PusTcCreator::builder()
|
||||
.with_service(17)
|
||||
.with_subservice(1)
|
||||
.with_service_type_id(17)
|
||||
.with_message_subtype_id(1)
|
||||
.with_apid(u11::new(0x02))
|
||||
.with_sequence_count(u14::new(0x34))
|
||||
.build();
|
||||
}
|
||||
PusTcBuilder::new()
|
||||
.with_service(17)
|
||||
.with_subservice(1)
|
||||
.with_service_type_id(17)
|
||||
.with_message_subtype_id(1)
|
||||
.with_apid(u11::new(0x02))
|
||||
.with_sequence_count(u14::new(0x34))
|
||||
.build()
|
||||
@@ -1085,8 +1169,7 @@ mod tests {
|
||||
let sph = SpHeader::new_for_unseg_tc(u11::new(0x02), u14::new(0x34), 0);
|
||||
PusTcCreator::new_simple(
|
||||
sph,
|
||||
17,
|
||||
1,
|
||||
MessageTypeId::new(17, 1),
|
||||
&[],
|
||||
CreatorConfig {
|
||||
set_ccsds_len: true,
|
||||
@@ -1102,8 +1185,7 @@ mod tests {
|
||||
let sph = SpHeader::new_for_unseg_tc(u11::new(0x02), u14::new(0x34), 0);
|
||||
PusTcCreator::new_simple(
|
||||
sph,
|
||||
17,
|
||||
1,
|
||||
MessageTypeId::new(17, 1),
|
||||
app_data,
|
||||
CreatorConfig {
|
||||
set_ccsds_len: true,
|
||||
@@ -1234,7 +1316,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_deserialization_alt_ctor() {
|
||||
let sph = SpHeader::new_for_unseg_tc(u11::new(0x02), u14::new(0x34), 0);
|
||||
let tc_header = PusTcSecondaryHeader::new_simple(17, 1);
|
||||
let tc_header = PusTcSecondaryHeader::new_simple(MessageTypeId::new(17, 1));
|
||||
let mut test_buf: [u8; 32] = [0; 32];
|
||||
let mut pus_tc =
|
||||
PusTcCreatorWithReservedAppData::new(&mut test_buf, sph, tc_header, 0, true).unwrap();
|
||||
@@ -1289,8 +1371,7 @@ mod tests {
|
||||
let sph = SpHeader::new_for_unseg_tc(u11::new(0x02), u14::new(0x34), 0);
|
||||
let mut tc = PusTcCreator::new_simple(
|
||||
sph,
|
||||
17,
|
||||
1,
|
||||
MessageTypeId::new(17, 1),
|
||||
&[],
|
||||
CreatorConfig {
|
||||
set_ccsds_len: false,
|
||||
@@ -1517,10 +1598,10 @@ mod tests {
|
||||
}
|
||||
|
||||
fn verify_test_tc_generic(tc: &(impl PusPacket + GenericPusTcSecondaryHeader)) {
|
||||
assert_eq!(PusPacket::service(tc), 17);
|
||||
assert_eq!(GenericPusTcSecondaryHeader::service(tc), 17);
|
||||
assert_eq!(PusPacket::subservice(tc), 1);
|
||||
assert_eq!(GenericPusTcSecondaryHeader::subservice(tc), 1);
|
||||
assert_eq!(PusPacket::service_type_id(tc), 17);
|
||||
assert_eq!(GenericPusTcSecondaryHeader::service_type_id(tc), 17);
|
||||
assert_eq!(PusPacket::message_subtype_id(tc), 1);
|
||||
assert_eq!(GenericPusTcSecondaryHeader::message_subtype_id(tc), 1);
|
||||
assert!(tc.sec_header_flag());
|
||||
assert_eq!(PusPacket::pus_version(tc).unwrap(), PusC);
|
||||
assert_eq!(tc.seq_count().value(), 0x34);
|
||||
@@ -1650,8 +1731,8 @@ mod tests {
|
||||
SequenceFlags::Unsegmented,
|
||||
u14::new(0x34),
|
||||
))
|
||||
.with_service(17)
|
||||
.with_subservice(1)
|
||||
.with_service_type_id(17)
|
||||
.with_message_subtype_id(1)
|
||||
.with_ack_flags(AckFlags::new_with_raw_value(u4::new(0b1010)))
|
||||
.with_source_id(0x2f2f)
|
||||
.with_checksum(false)
|
||||
@@ -1660,7 +1741,7 @@ mod tests {
|
||||
assert_eq!(tc.sequence_flags(), SequenceFlags::Unsegmented);
|
||||
assert_eq!(tc.apid().value(), 0x02);
|
||||
assert_eq!(tc.packet_type(), PacketType::Tc);
|
||||
assert_eq!(tc.service(), 17);
|
||||
assert_eq!(tc.subservice(), 1);
|
||||
assert_eq!(tc.service_type_id(), 17);
|
||||
assert_eq!(tc.message_subtype_id(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
//! true
|
||||
//! );
|
||||
//! println!("{:?}", pus_tc);
|
||||
//! assert_eq!(pus_tc.service(), 17);
|
||||
//! assert_eq!(pus_tc.subservice(), 1);
|
||||
//! assert_eq!(pus_tc.service_type_id(), 17);
|
||||
//! assert_eq!(pus_tc.message_subtype_id(), 1);
|
||||
//! assert_eq!(pus_tc.apid().value(), 0x02);
|
||||
//!
|
||||
//! // Serialize TC into a raw buffer
|
||||
@@ -29,15 +29,15 @@
|
||||
//!
|
||||
//! // Deserialize from the raw byte representation. No source ID, 0 spare bytes.
|
||||
//! let pus_tc_deserialized = PusTcReader::new(&test_buf, None, 0).expect("Deserialization failed");
|
||||
//! assert_eq!(pus_tc.service(), 17);
|
||||
//! assert_eq!(pus_tc.subservice(), 1);
|
||||
//! assert_eq!(pus_tc.service_type_id(), 17);
|
||||
//! assert_eq!(pus_tc.message_subtype_id(), 1);
|
||||
//! assert_eq!(pus_tc.apid().value(), 0x02);
|
||||
//! ```
|
||||
use crate::crc::{CRC_CCITT_FALSE, CRC_CCITT_FALSE_NO_TABLE};
|
||||
use crate::ecss::tc::{AckFlags, ACK_ALL};
|
||||
use crate::ecss::{
|
||||
crc_from_raw_data, sp_header_impls, user_data_from_raw,
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error, PusError, PusPacket, PusVersion,
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error, MessageTypeId, PusError, PusPacket, PusVersion,
|
||||
WritablePusPacket,
|
||||
};
|
||||
use crate::util::{UnsignedByteField, UnsignedEnum};
|
||||
@@ -74,33 +74,49 @@ enum AckOpts {
|
||||
|
||||
/// Assuming 8 bytes of source ID and 7 bytes of spare.
|
||||
pub const MAX_SEC_HEADER_LEN: usize = 18;
|
||||
/// Maximum allowed number of space bytes.
|
||||
pub const MAX_SPARE_BYTES: usize = 7;
|
||||
|
||||
/// Invalid number of spare bytes which must be between 0 and 7.
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone, thiserror::Error)]
|
||||
#[error("invalid number of spare bytes, must be between 0 and 7")]
|
||||
pub struct InvalidNumberOfSpareBytesError;
|
||||
|
||||
/// PUS version error.
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone, thiserror::Error)]
|
||||
#[error("invalid version, expected PUS A (1), got {0}")]
|
||||
pub struct VersionError(pub u8);
|
||||
|
||||
/// Trait for accessing PUS Telecommand secondary header fields.
|
||||
pub trait GenericPusTcSecondaryHeader {
|
||||
/// PUS version number.
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
/// Acknowledgment flags.
|
||||
fn ack_flags(&self) -> AckFlags;
|
||||
/// Service type identifier.
|
||||
fn service(&self) -> u8;
|
||||
/// Subservice type identifier.
|
||||
fn subservice(&self) -> u8;
|
||||
/// Source ID.
|
||||
fn source_id(&self) -> Option<UnsignedByteField>;
|
||||
/// Number of spare bytes.
|
||||
fn spare_bytes(&self) -> usize;
|
||||
}
|
||||
|
||||
/// PUS TC secondary header.
|
||||
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PusTcSecondaryHeader {
|
||||
/// Service type identifier.
|
||||
pub service: u8,
|
||||
/// Subservice type identifier.
|
||||
pub subservice: u8,
|
||||
/// Source ID.
|
||||
pub source_id: Option<UnsignedByteField>,
|
||||
/// Acknowledgment flags.
|
||||
pub ack: AckFlags,
|
||||
/// PUS version.
|
||||
pub version: PusVersion,
|
||||
spare_bytes: usize,
|
||||
}
|
||||
@@ -138,6 +154,8 @@ impl GenericPusTcSecondaryHeader for PusTcSecondaryHeader {
|
||||
}
|
||||
|
||||
impl PusTcSecondaryHeader {
|
||||
/// Constructor which allows modifying the service and subservice and sets
|
||||
/// default values for the other fields.
|
||||
#[inline]
|
||||
pub fn new_simple(service: u8, subservice: u8) -> Self {
|
||||
PusTcSecondaryHeader {
|
||||
@@ -150,6 +168,7 @@ impl PusTcSecondaryHeader {
|
||||
}
|
||||
}
|
||||
|
||||
/// Generic constructor.
|
||||
#[inline]
|
||||
pub fn new(
|
||||
service: u8,
|
||||
@@ -176,6 +195,7 @@ impl PusTcSecondaryHeader {
|
||||
self.spare_bytes = spare_bytes;
|
||||
}
|
||||
|
||||
/// Length of the written secondary header in bytes.
|
||||
pub fn written_len(&self) -> usize {
|
||||
let mut len = 3 + self.spare_bytes;
|
||||
if let Some(source_id) = self.source_id {
|
||||
@@ -184,6 +204,7 @@ impl PusTcSecondaryHeader {
|
||||
len
|
||||
}
|
||||
|
||||
/// Converts the secondary header into a vector of bytes.
|
||||
#[cfg(feature = "alloc")]
|
||||
pub fn to_vec(&self) -> Result<Vec<u8>, ByteConversionError> {
|
||||
let mut buf = alloc::vec![0; self.written_len()];
|
||||
@@ -191,6 +212,7 @@ impl PusTcSecondaryHeader {
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// Write the secondary header to a provided buffer.
|
||||
pub fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
if buf.len() < self.written_len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
@@ -216,6 +238,7 @@ impl PusTcSecondaryHeader {
|
||||
Ok(current_idx)
|
||||
}
|
||||
|
||||
/// Read the secondary header from a raw byte slice.
|
||||
pub fn from_bytes(
|
||||
data: &[u8],
|
||||
source_id_size: Option<usize>,
|
||||
@@ -268,6 +291,7 @@ impl PusTcSecondaryHeader {
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PusTcCreator<'app_data> {
|
||||
sp_header: SpHeader,
|
||||
/// Secondary header.
|
||||
pub sec_header: PusTcSecondaryHeader,
|
||||
app_data: &'app_data [u8],
|
||||
}
|
||||
@@ -323,6 +347,7 @@ impl<'app_data> PusTcCreator<'app_data> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructor without application data.
|
||||
#[inline]
|
||||
pub fn new_no_app_data(
|
||||
sp_header: SpHeader,
|
||||
@@ -332,26 +357,31 @@ impl<'app_data> PusTcCreator<'app_data> {
|
||||
Self::new(sp_header, sec_header, &[], set_ccsds_len)
|
||||
}
|
||||
|
||||
/// Space packet header.
|
||||
#[inline]
|
||||
pub fn sp_header(&self) -> &SpHeader {
|
||||
&self.sp_header
|
||||
}
|
||||
|
||||
/// Mutable access to the space packet header.
|
||||
#[inline]
|
||||
pub fn sp_header_mut(&mut self) -> &mut SpHeader {
|
||||
&mut self.sp_header
|
||||
}
|
||||
|
||||
/// Set the acknowledgment flags.
|
||||
#[inline]
|
||||
pub fn set_ack_field(&mut self, ack: AckFlags) {
|
||||
self.sec_header.ack = ack;
|
||||
}
|
||||
|
||||
/// Set the source ID.
|
||||
#[inline]
|
||||
pub fn set_source_id(&mut self, source_id: Option<UnsignedByteField>) {
|
||||
self.sec_header.source_id = source_id;
|
||||
}
|
||||
|
||||
/// Application data slice.
|
||||
#[inline]
|
||||
pub fn app_data(&'app_data self) -> &'app_data [u8] {
|
||||
self.user_data()
|
||||
@@ -397,6 +427,7 @@ impl<'app_data> PusTcCreator<'app_data> {
|
||||
digest.finalize()
|
||||
}
|
||||
|
||||
/// Append the raw PUS byte representation to a provided vector.
|
||||
#[cfg(feature = "alloc")]
|
||||
pub fn append_to_vec(&self, vec: &mut Vec<u8>) -> usize {
|
||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||
@@ -499,11 +530,23 @@ impl PusPacket for PusTcCreator<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
#[inline]
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
});
|
||||
#[inline]
|
||||
fn message_type_id(&self) -> MessageTypeId {
|
||||
MessageTypeId {
|
||||
type_id: self.service_type_id(),
|
||||
subtype_id: self.message_subtype_id(),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.sec_header.service
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.sec_header.subservice
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn user_data(&self) -> &[u8] {
|
||||
@@ -604,6 +647,7 @@ impl<'buf> PusTcCreatorWithReservedAppData<'buf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Length of the written TC packet.
|
||||
#[inline]
|
||||
pub const fn len_written(&self) -> usize {
|
||||
self.full_len
|
||||
@@ -621,6 +665,7 @@ impl<'buf> PusTcCreatorWithReservedAppData<'buf> {
|
||||
&self.buf[self.app_data_offset..self.full_len - 2]
|
||||
}
|
||||
|
||||
/// Application data length.
|
||||
#[inline]
|
||||
pub fn app_data_len(&self) -> usize {
|
||||
self.full_len - 2 - self.app_data_offset
|
||||
@@ -745,26 +790,31 @@ impl<'raw_data> PusTcReader<'raw_data> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Application data slice.
|
||||
#[inline]
|
||||
pub fn app_data(&self) -> &[u8] {
|
||||
self.user_data()
|
||||
}
|
||||
|
||||
/// Full raw data slice.
|
||||
#[inline]
|
||||
pub fn raw_data(&self) -> &[u8] {
|
||||
self.raw_data
|
||||
}
|
||||
|
||||
/// Length of the packed PUS TC packet in bytes.
|
||||
#[inline]
|
||||
pub fn len_packed(&self) -> usize {
|
||||
self.sp_header.packet_len()
|
||||
}
|
||||
|
||||
/// Space packet header.
|
||||
#[inline]
|
||||
pub fn sp_header(&self) -> &SpHeader {
|
||||
&self.sp_header
|
||||
}
|
||||
|
||||
/// CRC16 checksum value.
|
||||
#[inline]
|
||||
pub fn crc16(&self) -> u16 {
|
||||
self.crc16
|
||||
@@ -793,14 +843,28 @@ impl CcsdsPacket for PusTcReader<'_> {
|
||||
|
||||
impl PusPacket for PusTcReader<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
#[inline]
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
});
|
||||
|
||||
#[inline]
|
||||
fn message_type_id(&self) -> MessageTypeId {
|
||||
MessageTypeId {
|
||||
type_id: self.service_type_id(),
|
||||
subtype_id: self.message_subtype_id(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.sec_header.service
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.sec_header.subservice
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn has_checksum(&self) -> bool {
|
||||
true
|
||||
@@ -1229,9 +1293,9 @@ mod tests {
|
||||
}
|
||||
|
||||
fn verify_test_tc_generic(tc: &(impl PusPacket + GenericPusTcSecondaryHeader)) {
|
||||
assert_eq!(PusPacket::service(tc), 17);
|
||||
assert_eq!(PusPacket::service_type_id(tc), 17);
|
||||
assert_eq!(GenericPusTcSecondaryHeader::service(tc), 17);
|
||||
assert_eq!(PusPacket::subservice(tc), 1);
|
||||
assert_eq!(PusPacket::message_subtype_id(tc), 1);
|
||||
assert_eq!(GenericPusTcSecondaryHeader::subservice(tc), 1);
|
||||
assert!(tc.sec_header_flag());
|
||||
assert_eq!(PusPacket::pus_version(tc).unwrap(), PusVersion::PusA);
|
||||
|
||||
385
src/ecss/tm.rs
385
src/ecss/tm.rs
@@ -6,7 +6,7 @@
|
||||
//! ```rust
|
||||
//! use spacepackets::time::cds::CdsTime;
|
||||
//! use spacepackets::SpHeader;
|
||||
//! use spacepackets::ecss::tm::{PusTmCreator, PusTmReader, PusTmSecondaryHeader, CreatorConfig};
|
||||
//! use spacepackets::ecss::tm::{MessageTypeId, PusTmCreator, PusTmReader, PusTmSecondaryHeader, CreatorConfig};
|
||||
//! use arbitrary_int::u11;
|
||||
//!
|
||||
//! let mut time_buf: [u8; 7] = [0; 7];
|
||||
@@ -17,12 +17,12 @@
|
||||
//! // Create a ping telemetry with no user source data
|
||||
//! let ping_tm = PusTmCreator::new_no_source_data(
|
||||
//! SpHeader::new_from_apid(u11::new(0x02)),
|
||||
//! PusTmSecondaryHeader::new_simple(17, 2, &time_buf),
|
||||
//! PusTmSecondaryHeader::new_simple(MessageTypeId::new(17, 2), &time_buf),
|
||||
//! CreatorConfig::default()
|
||||
//! );
|
||||
//! println!("{:?}", ping_tm);
|
||||
//! assert_eq!(ping_tm.service(), 17);
|
||||
//! assert_eq!(ping_tm.subservice(), 2);
|
||||
//! assert_eq!(ping_tm.service_type_id(), 17);
|
||||
//! assert_eq!(ping_tm.message_subtype_id(), 2);
|
||||
//! assert_eq!(ping_tm.apid().value(), 0x02);
|
||||
//!
|
||||
//! // Serialize TM into a raw buffer
|
||||
@@ -36,27 +36,27 @@
|
||||
//! // Deserialize from the raw byte representation
|
||||
//! let ping_tm_reader = PusTmReader::new(&test_buf, 7).expect("Deserialization failed");
|
||||
//! assert_eq!(written_size, ping_tm_reader.packet_len());
|
||||
//! assert_eq!(ping_tm_reader.service(), 17);
|
||||
//! assert_eq!(ping_tm_reader.subservice(), 2);
|
||||
//! assert_eq!(ping_tm_reader.service_type_id(), 17);
|
||||
//! assert_eq!(ping_tm_reader.message_subtype_id(), 2);
|
||||
//! assert_eq!(ping_tm_reader.apid().value(), 0x02);
|
||||
//! assert_eq!(ping_tm_reader.timestamp(), &time_buf);
|
||||
//!
|
||||
//! // Alternative builder API
|
||||
//! let pus_tm_by_builder = PusTmCreator::builder()
|
||||
//! .with_service(17)
|
||||
//! .with_subservice(2)
|
||||
//! .with_service_type_id(17)
|
||||
//! .with_message_subtype_id(2)
|
||||
//! .with_apid(u11::new(0x02))
|
||||
//! .with_timestamp(&time_buf)
|
||||
//! .build();
|
||||
//! assert_eq!(pus_tm_by_builder, ping_tm);
|
||||
//! ```
|
||||
use crate::crc::{CRC_CCITT_FALSE, CRC_CCITT_FALSE_NO_TABLE};
|
||||
pub use crate::ecss::CreatorConfig;
|
||||
use crate::ecss::{
|
||||
calc_pus_crc16, crc_from_raw_data, sp_header_impls, user_data_from_raw,
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error, PusError, PusPacket, PusVersion,
|
||||
WritablePusPacket,
|
||||
};
|
||||
pub use crate::ecss::{CreatorConfig, MessageTypeId};
|
||||
use crate::{
|
||||
ByteConversionError, CcsdsPacket, PacketId, PacketSequenceControl, PacketType, SequenceFlags,
|
||||
SpHeader, CCSDS_HEADER_LEN, MAX_APID,
|
||||
@@ -78,40 +78,63 @@ use self::zc::PusTmSecHeaderWithoutTimestamp;
|
||||
|
||||
use super::verify_crc16_ccitt_false_from_raw_to_pus_error_no_table;
|
||||
|
||||
/// Marker trait for PUS telemetry packets.
|
||||
pub trait IsPusTelemetry {}
|
||||
|
||||
/// Length without timestamp
|
||||
pub const PUS_TM_MIN_SEC_HEADER_LEN: usize = 7;
|
||||
/// Minimum length of a PUS telemetry packet without source data and timestamp
|
||||
pub const PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA: usize = CCSDS_HEADER_LEN + PUS_TM_MIN_SEC_HEADER_LEN;
|
||||
|
||||
/// Generic properties of a PUS TM secondary header.
|
||||
pub trait GenericPusTmSecondaryHeader {
|
||||
/// PUS version.
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
/// Spacecraft time reference status.
|
||||
fn sc_time_ref_status(&self) -> u4;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
fn msg_counter(&self) -> u16;
|
||||
/// Message type ID.
|
||||
fn message_type_id(&self) -> MessageTypeId;
|
||||
/// Message counter for the message type.
|
||||
fn msg_type_counter(&self) -> u16;
|
||||
|
||||
/// Destination ID.
|
||||
fn dest_id(&self) -> u16;
|
||||
|
||||
/// Service type ID.
|
||||
#[inline]
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.message_type_id().type_id
|
||||
}
|
||||
|
||||
/// Message subtype ID.
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.message_type_id().subtype_id
|
||||
}
|
||||
}
|
||||
|
||||
/// [zerocopy] support module.
|
||||
pub mod zc {
|
||||
use super::GenericPusTmSecondaryHeader;
|
||||
use crate::ecss::{PusError, PusVersion};
|
||||
use crate::ecss::{MessageTypeId, PusError, PusVersion};
|
||||
use arbitrary_int::{traits::Integer as _, u4};
|
||||
use zerocopy::{FromBytes, Immutable, IntoBytes, NetworkEndian, Unaligned, U16};
|
||||
|
||||
/// PUS TM secondary header without a timestamp.
|
||||
#[derive(FromBytes, IntoBytes, Immutable, Unaligned)]
|
||||
#[repr(C)]
|
||||
pub struct PusTmSecHeaderWithoutTimestamp {
|
||||
pus_version_and_sc_time_ref_status: u8,
|
||||
service: u8,
|
||||
subservice: u8,
|
||||
service_type_id: u8,
|
||||
message_subtype_id: u8,
|
||||
msg_counter: U16<NetworkEndian>,
|
||||
dest_id: U16<NetworkEndian>,
|
||||
}
|
||||
|
||||
pub struct PusTmSecHeader<'slice> {
|
||||
/// PUS TM secondary header with timestamp.
|
||||
pub struct PusTmSecHeader<'time> {
|
||||
pub(crate) zc_header: PusTmSecHeaderWithoutTimestamp,
|
||||
pub(crate) timestamp: &'slice [u8],
|
||||
pub(crate) timestamp: &'time [u8],
|
||||
}
|
||||
|
||||
impl TryFrom<crate::ecss::tm::PusTmSecondaryHeader<'_>> for PusTmSecHeaderWithoutTimestamp {
|
||||
@@ -125,8 +148,8 @@ pub mod zc {
|
||||
Ok(PusTmSecHeaderWithoutTimestamp {
|
||||
pus_version_and_sc_time_ref_status: ((header.pus_version as u8) << 4)
|
||||
| header.sc_time_ref_status.as_u8(),
|
||||
service: header.service,
|
||||
subservice: header.subservice,
|
||||
service_type_id: header.service_type_id(),
|
||||
message_subtype_id: header.message_subtype_id(),
|
||||
msg_counter: U16::from(header.msg_counter),
|
||||
dest_id: U16::from(header.dest_id),
|
||||
})
|
||||
@@ -146,18 +169,27 @@ pub mod zc {
|
||||
u4::new(self.pus_version_and_sc_time_ref_status & 0b1111)
|
||||
}
|
||||
|
||||
/// Message type ID.
|
||||
#[inline]
|
||||
fn service(&self) -> u8 {
|
||||
self.service
|
||||
fn message_type_id(&self) -> MessageTypeId {
|
||||
MessageTypeId {
|
||||
type_id: self.service_type_id,
|
||||
subtype_id: self.message_subtype_id,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8 {
|
||||
self.subservice
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.service_type_id
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn msg_counter(&self) -> u16 {
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.message_subtype_id
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn msg_type_counter(&self) -> u16 {
|
||||
self.msg_counter.get()
|
||||
}
|
||||
|
||||
@@ -168,35 +200,42 @@ pub mod zc {
|
||||
}
|
||||
}
|
||||
|
||||
/// PUS TM secondary header.
|
||||
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PusTmSecondaryHeader<'stamp> {
|
||||
pus_version: PusVersion,
|
||||
/// Spacecraft time reference status.
|
||||
pub sc_time_ref_status: u4,
|
||||
pub service: u8,
|
||||
pub subservice: u8,
|
||||
/// Message type ID.
|
||||
pub message_type_id: MessageTypeId,
|
||||
/// Message counter for the message service type ID.
|
||||
pub msg_counter: u16,
|
||||
/// Destination ID.
|
||||
pub dest_id: u16,
|
||||
/// Raw timestamp slice.
|
||||
pub timestamp: &'stamp [u8],
|
||||
}
|
||||
|
||||
impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
/// Constructor where only the message type ID and timestamp are specified. The other fields
|
||||
/// are set to default values.
|
||||
#[inline]
|
||||
pub fn new_simple(service: u8, subservice: u8, timestamp: &'stamp [u8]) -> Self {
|
||||
Self::new(service, subservice, 0, 0, timestamp)
|
||||
pub fn new_simple(message_type_id: MessageTypeId, timestamp: &'stamp [u8]) -> Self {
|
||||
Self::new(message_type_id, 0, 0, timestamp)
|
||||
}
|
||||
|
||||
/// Like [Self::new_simple] but without a timestamp.
|
||||
#[inline]
|
||||
pub fn new_simple_no_timestamp(service: u8, subservice: u8) -> Self {
|
||||
Self::new(service, subservice, 0, 0, &[])
|
||||
pub fn new_simple_no_timestamp(message_type_id: MessageTypeId) -> Self {
|
||||
Self::new(message_type_id, 0, 0, &[])
|
||||
}
|
||||
|
||||
/// Generic constructor.
|
||||
#[inline]
|
||||
pub fn new(
|
||||
service: u8,
|
||||
subservice: u8,
|
||||
message_type_id: MessageTypeId,
|
||||
msg_counter: u16,
|
||||
dest_id: u16,
|
||||
timestamp: &'stamp [u8],
|
||||
@@ -204,8 +243,7 @@ impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
PusTmSecondaryHeader {
|
||||
pus_version: PusVersion::PusC,
|
||||
sc_time_ref_status: u4::new(0),
|
||||
service,
|
||||
subservice,
|
||||
message_type_id,
|
||||
msg_counter,
|
||||
dest_id,
|
||||
timestamp,
|
||||
@@ -225,17 +263,12 @@ impl GenericPusTmSecondaryHeader for PusTmSecondaryHeader<'_> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service(&self) -> u8 {
|
||||
self.service
|
||||
fn message_type_id(&self) -> MessageTypeId {
|
||||
self.message_type_id
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8 {
|
||||
self.subservice
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn msg_counter(&self) -> u16 {
|
||||
fn msg_type_counter(&self) -> u16 {
|
||||
self.msg_counter
|
||||
}
|
||||
|
||||
@@ -257,9 +290,8 @@ impl<'slice> TryFrom<zc::PusTmSecHeader<'slice>> for PusTmSecondaryHeader<'slice
|
||||
Ok(PusTmSecondaryHeader {
|
||||
pus_version: version.unwrap(),
|
||||
sc_time_ref_status: sec_header.zc_header.sc_time_ref_status(),
|
||||
service: sec_header.zc_header.service(),
|
||||
subservice: sec_header.zc_header.subservice(),
|
||||
msg_counter: sec_header.zc_header.msg_counter(),
|
||||
message_type_id: sec_header.zc_header.message_type_id(),
|
||||
msg_counter: sec_header.zc_header.msg_type_counter(),
|
||||
dest_id: sec_header.zc_header.dest_id(),
|
||||
timestamp: sec_header.timestamp,
|
||||
})
|
||||
@@ -283,7 +315,9 @@ impl<'slice> TryFrom<zc::PusTmSecHeader<'slice>> for PusTmSecondaryHeader<'slice
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PusTmCreator<'time, 'src_data> {
|
||||
/// Space packet header.
|
||||
pub sp_header: SpHeader,
|
||||
/// Secondary header.
|
||||
#[cfg_attr(feature = "serde", serde(borrow))]
|
||||
pub sec_header: PusTmSecondaryHeader<'time>,
|
||||
source_data: &'src_data [u8],
|
||||
@@ -326,11 +360,12 @@ impl<'time, 'src_data> PusTmCreator<'time, 'src_data> {
|
||||
pus_tm
|
||||
}
|
||||
|
||||
/// Simple constructor which builds the [PusTmSecondaryHeader] internally from the
|
||||
/// provided arguments.
|
||||
#[inline]
|
||||
pub fn new_simple(
|
||||
sp_header: SpHeader,
|
||||
service: u8,
|
||||
subservice: u8,
|
||||
message_type_id: MessageTypeId,
|
||||
time_provider: &impl TimeWriter,
|
||||
stamp_buf: &'time mut [u8],
|
||||
source_data: &'src_data [u8],
|
||||
@@ -338,10 +373,11 @@ impl<'time, 'src_data> PusTmCreator<'time, 'src_data> {
|
||||
) -> Result<Self, TimestampError> {
|
||||
let stamp_size = time_provider.write_to_bytes(stamp_buf)?;
|
||||
let sec_header =
|
||||
PusTmSecondaryHeader::new_simple(service, subservice, &stamp_buf[0..stamp_size]);
|
||||
PusTmSecondaryHeader::new_simple(message_type_id, &stamp_buf[0..stamp_size]);
|
||||
Ok(Self::new(sp_header, sec_header, source_data, packet_config))
|
||||
}
|
||||
|
||||
/// Constructor for PUS TM packets without source data.
|
||||
#[inline]
|
||||
pub fn new_no_source_data(
|
||||
sp_header: SpHeader,
|
||||
@@ -351,50 +387,60 @@ impl<'time, 'src_data> PusTmCreator<'time, 'src_data> {
|
||||
Self::new(sp_header, sec_header, &[], packet_config)
|
||||
}
|
||||
|
||||
/// Builder API.
|
||||
pub fn builder() -> PusTmBuilder<'time, 'src_data> {
|
||||
PusTmBuilder::new()
|
||||
}
|
||||
|
||||
/// Does the packet have a checksum?
|
||||
#[inline]
|
||||
pub fn has_checksum(&self) -> bool {
|
||||
self.has_checksum
|
||||
}
|
||||
|
||||
/// Raw timestamp slice.
|
||||
#[inline]
|
||||
pub fn timestamp(&self) -> &[u8] {
|
||||
self.sec_header.timestamp
|
||||
}
|
||||
|
||||
/// Raw source data slice.
|
||||
#[inline]
|
||||
pub fn source_data(&self) -> &[u8] {
|
||||
self.source_data
|
||||
}
|
||||
|
||||
/// Servcie type ID.
|
||||
#[inline]
|
||||
pub fn service(&self) -> u8 {
|
||||
self.sec_header.service
|
||||
pub fn service_type_id(&self) -> u8 {
|
||||
self.sec_header.service_type_id()
|
||||
}
|
||||
|
||||
/// Message subtype ID.
|
||||
#[inline]
|
||||
pub fn subservice(&self) -> u8 {
|
||||
self.sec_header.subservice
|
||||
pub fn message_subtype_id(&self) -> u8 {
|
||||
self.sec_header.message_subtype_id()
|
||||
}
|
||||
|
||||
/// Application Process Identifier (APID).
|
||||
#[inline]
|
||||
pub fn apid(&self) -> u11 {
|
||||
self.sp_header.packet_id.apid
|
||||
}
|
||||
|
||||
/// Set the destination ID.
|
||||
#[inline]
|
||||
pub fn set_dest_id(&mut self, dest_id: u16) {
|
||||
self.sec_header.dest_id = dest_id;
|
||||
}
|
||||
|
||||
/// Set the message counter for the service type ID.
|
||||
#[inline]
|
||||
pub fn set_msg_counter(&mut self, msg_counter: u16) {
|
||||
self.sec_header.msg_counter = msg_counter
|
||||
}
|
||||
|
||||
/// Set the spacecraft time reference status.
|
||||
#[inline]
|
||||
pub fn set_sc_time_ref_status(&mut self, sc_time_ref_status: u4) {
|
||||
self.sec_header.sc_time_ref_status = sc_time_ref_status;
|
||||
@@ -567,9 +613,7 @@ impl PusPacket for PusTmCreator<'_, '_> {
|
||||
|
||||
delegate!(to self.sec_header {
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
fn message_type_id(&self) -> MessageTypeId;
|
||||
});
|
||||
|
||||
#[inline]
|
||||
@@ -590,14 +634,21 @@ impl GenericPusTmSecondaryHeader for PusTmCreator<'_, '_> {
|
||||
delegate!(to self.sec_header {
|
||||
#[inline]
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
/// Message type ID.
|
||||
fn message_type_id(&self) -> MessageTypeId;
|
||||
|
||||
/// Service type ID.
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
fn service_type_id(&self) -> u8;
|
||||
|
||||
/// Message subtype ID.
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
fn message_subtype_id(&self) -> u8;
|
||||
|
||||
#[inline]
|
||||
fn dest_id(&self) -> u16;
|
||||
#[inline]
|
||||
fn msg_counter(&self) -> u16;
|
||||
fn msg_type_counter(&self) -> u16;
|
||||
#[inline]
|
||||
fn sc_time_ref_status(&self) -> u4;
|
||||
});
|
||||
@@ -605,6 +656,7 @@ impl GenericPusTmSecondaryHeader for PusTmCreator<'_, '_> {
|
||||
|
||||
impl IsPusTelemetry for PusTmCreator<'_, '_> {}
|
||||
|
||||
/// PUS TM bulder API.
|
||||
#[derive(Debug)]
|
||||
pub struct PusTmBuilder<'time, 'src_data> {
|
||||
sp_header: SpHeader,
|
||||
@@ -620,6 +672,7 @@ impl Default for PusTmBuilder<'_, '_> {
|
||||
}
|
||||
|
||||
impl PusTmBuilder<'_, '_> {
|
||||
/// Constructor.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
sp_header: SpHeader::new(
|
||||
@@ -627,18 +680,28 @@ impl PusTmBuilder<'_, '_> {
|
||||
PacketSequenceControl::new(SequenceFlags::Unsegmented, u14::new(0)),
|
||||
0,
|
||||
),
|
||||
sec_header: PusTmSecondaryHeader::new(0, 0, 0, 0, &[]),
|
||||
sec_header: PusTmSecondaryHeader::new(
|
||||
MessageTypeId {
|
||||
type_id: 0,
|
||||
subtype_id: 0,
|
||||
},
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
),
|
||||
source_data: &[],
|
||||
has_checksum: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the application process identifier (APID).
|
||||
#[inline]
|
||||
pub fn with_apid(mut self, apid: u11) -> Self {
|
||||
self.sp_header.packet_id.set_apid(apid);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the packet ID.
|
||||
#[inline]
|
||||
pub fn with_packet_id(mut self, mut packet_id: PacketId) -> Self {
|
||||
packet_id.packet_type = PacketType::Tc;
|
||||
@@ -646,48 +709,63 @@ impl PusTmBuilder<'_, '_> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the packet sequence control.
|
||||
#[inline]
|
||||
pub fn with_packet_sequence_control(mut self, psc: PacketSequenceControl) -> Self {
|
||||
self.sp_header.psc = psc;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the sequence count.
|
||||
#[inline]
|
||||
pub fn with_sequence_count(mut self, seq_count: u14) -> Self {
|
||||
self.sp_header.psc.seq_count = seq_count;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the message type ID.
|
||||
#[inline]
|
||||
pub fn with_service(mut self, service: u8) -> Self {
|
||||
self.sec_header.service = service;
|
||||
pub fn with_message_type_id(mut self, message_type_id: MessageTypeId) -> Self {
|
||||
self.sec_header.message_type_id = message_type_id;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the service type ID.
|
||||
#[inline]
|
||||
pub fn with_subservice(mut self, service: u8) -> Self {
|
||||
self.sec_header.subservice = service;
|
||||
pub fn with_service_type_id(mut self, type_id: u8) -> Self {
|
||||
self.sec_header.message_type_id.type_id = type_id;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the message subtype ID.
|
||||
#[inline]
|
||||
pub fn with_message_subtype_id(mut self, subtype_id: u8) -> Self {
|
||||
self.sec_header.message_type_id.subtype_id = subtype_id;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the destination ID.
|
||||
#[inline]
|
||||
pub fn with_dest_id(mut self, dest_id: u16) -> Self {
|
||||
self.sec_header.dest_id = dest_id;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the message counter for the service type ID.
|
||||
#[inline]
|
||||
pub fn with_msg_counter(mut self, msg_counter: u16) -> Self {
|
||||
self.sec_header.msg_counter = msg_counter;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the spacecraft time reference status.
|
||||
#[inline]
|
||||
pub fn with_sc_time_ref_status(mut self, sc_time_ref_status: u4) -> Self {
|
||||
self.sec_header.sc_time_ref_status = sc_time_ref_status;
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable or disable checksum generation.
|
||||
#[inline]
|
||||
pub fn with_checksum(mut self, has_checksum: bool) -> Self {
|
||||
self.has_checksum = has_checksum;
|
||||
@@ -696,6 +774,7 @@ impl PusTmBuilder<'_, '_> {
|
||||
}
|
||||
|
||||
impl<'src_data> PusTmBuilder<'_, 'src_data> {
|
||||
/// Set the source data.
|
||||
#[inline]
|
||||
pub fn with_source_data(mut self, source_data: &'src_data [u8]) -> Self {
|
||||
self.source_data = source_data;
|
||||
@@ -704,6 +783,7 @@ impl<'src_data> PusTmBuilder<'_, 'src_data> {
|
||||
}
|
||||
|
||||
impl<'time> PusTmBuilder<'time, '_> {
|
||||
/// Set the timestamp.
|
||||
#[inline]
|
||||
pub fn with_timestamp(mut self, timestamp: &'time [u8]) -> Self {
|
||||
self.sec_header.timestamp = timestamp;
|
||||
@@ -712,6 +792,7 @@ impl<'time> PusTmBuilder<'time, '_> {
|
||||
}
|
||||
|
||||
impl<'time, 'src_data> PusTmBuilder<'time, 'src_data> {
|
||||
/// Constructor.
|
||||
pub fn build(self) -> PusTmCreator<'time, 'src_data> {
|
||||
PusTmCreator::new(
|
||||
self.sp_header,
|
||||
@@ -812,6 +893,7 @@ impl<'buf> PusTmCreatorWithReservedSourceData<'buf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Length of the full packet written to the buffer.
|
||||
#[inline]
|
||||
pub const fn len_written(&self) -> usize {
|
||||
self.full_len
|
||||
@@ -837,6 +919,7 @@ impl<'buf> PusTmCreatorWithReservedSourceData<'buf> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Length of the source data.
|
||||
#[inline]
|
||||
pub fn source_data_len(&self) -> usize {
|
||||
let mut len = self.full_len - self.source_data_offset;
|
||||
@@ -886,11 +969,16 @@ impl<'buf> PusTmCreatorWithReservedSourceData<'buf> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration options for the [PusTmReader].
|
||||
///
|
||||
/// This includes managed parameters which can not be deduced from the raw byte slice itself.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct ReaderConfig {
|
||||
/// Expected timestamp length.
|
||||
pub timestamp_len: usize,
|
||||
/// Does the packet have a checksum?
|
||||
pub has_checksum: bool,
|
||||
}
|
||||
|
||||
@@ -910,7 +998,9 @@ pub struct ReaderConfig {
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PusTmReader<'raw_data> {
|
||||
/// Space packet header.
|
||||
pub sp_header: SpHeader,
|
||||
/// PUS TM secondary header.
|
||||
pub sec_header: PusTmSecondaryHeader<'raw_data>,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
raw_data: &'raw_data [u8],
|
||||
@@ -968,6 +1058,7 @@ impl<'raw_data> PusTmReader<'raw_data> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructor which does not perform checksum verification.
|
||||
pub fn new_no_checksum_verification(
|
||||
slice: &'raw_data [u8],
|
||||
reader_config: ReaderConfig,
|
||||
@@ -1029,41 +1120,49 @@ impl<'raw_data> PusTmReader<'raw_data> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Length of the full packed PUS TM packet.
|
||||
#[inline]
|
||||
pub fn len_packed(&self) -> usize {
|
||||
self.sp_header.packet_len()
|
||||
}
|
||||
|
||||
/// Source data slice.
|
||||
#[inline]
|
||||
pub fn source_data(&self) -> &[u8] {
|
||||
self.user_data()
|
||||
}
|
||||
|
||||
/// Service type ID.
|
||||
#[inline]
|
||||
pub fn service(&self) -> u8 {
|
||||
self.sec_header.service
|
||||
pub fn service_type_id(&self) -> u8 {
|
||||
self.sec_header.service_type_id()
|
||||
}
|
||||
|
||||
/// Message subtype ID.
|
||||
#[inline]
|
||||
pub fn subservice(&self) -> u8 {
|
||||
self.sec_header.subservice
|
||||
pub fn message_subtype_id(&self) -> u8 {
|
||||
self.sec_header.message_subtype_id()
|
||||
}
|
||||
|
||||
/// Full packet length.
|
||||
#[inline]
|
||||
pub fn packet_len(&self) -> usize {
|
||||
self.sp_header.packet_len()
|
||||
}
|
||||
|
||||
/// Application Process Identifier (APID).
|
||||
#[inline]
|
||||
pub fn apid(&self) -> u11 {
|
||||
self.sp_header.packet_id.apid
|
||||
}
|
||||
|
||||
/// Raw timestamp slice.
|
||||
#[inline]
|
||||
pub fn timestamp(&self) -> &[u8] {
|
||||
self.sec_header.timestamp
|
||||
}
|
||||
|
||||
/// Does the packet have a checksum?
|
||||
#[inline]
|
||||
pub fn checksum(&self) -> Option<u16> {
|
||||
self.checksum
|
||||
@@ -1102,10 +1201,15 @@ impl PusPacket for PusTmReader<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
#[inline]
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
fn message_type_id(&self) -> MessageTypeId;
|
||||
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
fn service_type_id(&self) -> u8;
|
||||
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8;
|
||||
});
|
||||
|
||||
#[inline]
|
||||
@@ -1129,13 +1233,15 @@ impl GenericPusTmSecondaryHeader for PusTmReader<'_> {
|
||||
#[inline]
|
||||
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
fn message_type_id(&self) -> MessageTypeId;
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
fn service_type_id(&self) -> u8;
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8;
|
||||
#[inline]
|
||||
fn dest_id(&self) -> u16;
|
||||
#[inline]
|
||||
fn msg_counter(&self) -> u16;
|
||||
fn msg_type_counter(&self) -> u16;
|
||||
#[inline]
|
||||
fn sc_time_ref_status(&self) -> u4;
|
||||
});
|
||||
@@ -1202,6 +1308,7 @@ impl<'raw> PusTmZeroCopyWriter<'raw> {
|
||||
Some(writer)
|
||||
}
|
||||
|
||||
/// Set the application process identifier (APID).
|
||||
#[inline]
|
||||
pub fn set_apid(&mut self, apid: u11) {
|
||||
// Clear APID part of the raw packet ID
|
||||
@@ -1241,6 +1348,7 @@ impl<'raw> PusTmZeroCopyWriter<'raw> {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Set the sequence count in the CCSDS packet header.
|
||||
#[inline]
|
||||
pub fn set_seq_count(&mut self, seq_count: u14) {
|
||||
let new_psc = (u16::from_be_bytes(self.raw_tm[2..4].try_into().unwrap()) & 0xC000)
|
||||
@@ -1257,6 +1365,24 @@ impl<'raw> PusTmZeroCopyWriter<'raw> {
|
||||
self.raw_tm[slice_len - 2..].copy_from_slice(&crc16.to_be_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.raw_tm[7]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.raw_tm[8]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn message_type_id(&self) -> MessageTypeId {
|
||||
MessageTypeId {
|
||||
type_id: self.service_type_id(),
|
||||
subtype_id: self.message_subtype_id(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CcsdsPacket for PusTmZeroCopyWriter<'_> {
|
||||
@@ -1287,19 +1413,24 @@ impl PusPacket for PusTmZeroCopyWriter<'_> {
|
||||
self.sec_header_without_timestamp().pus_version()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service(&self) -> u8 {
|
||||
self.raw_tm[7]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn has_checksum(&self) -> bool {
|
||||
self.has_checksum
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8 {
|
||||
self.raw_tm[8]
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.service_type_id()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.message_subtype_id()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn message_type_id(&self) -> MessageTypeId {
|
||||
self.message_type_id()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -1334,20 +1465,25 @@ impl GenericPusTmSecondaryHeader for PusTmZeroCopyWriter<'_> {
|
||||
#[inline]
|
||||
fn sc_time_ref_status(&self) -> u4;
|
||||
#[inline]
|
||||
fn msg_counter(&self) -> u16;
|
||||
fn msg_type_counter(&self) -> u16;
|
||||
#[inline]
|
||||
fn dest_id(&self) -> u16;
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service(&self) -> u8 {
|
||||
PusPacket::service(self)
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.service_type_id()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8 {
|
||||
PusPacket::subservice(self)
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.message_subtype_id()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn message_type_id(&self) -> MessageTypeId {
|
||||
self.message_type_id()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1367,7 +1503,7 @@ mod tests {
|
||||
|
||||
fn base_ping_reply_full_ctor<'a, 'b>(timestamp: &'a [u8]) -> PusTmCreator<'a, 'b> {
|
||||
let sph = SpHeader::new_for_unseg_tm(u11::new(0x123), u14::new(0x234), 0);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(MessageTypeId::new(17, 2), timestamp);
|
||||
PusTmCreator::new_no_source_data(sph, tm_header, CreatorConfig::default())
|
||||
}
|
||||
|
||||
@@ -1379,23 +1515,23 @@ mod tests {
|
||||
return PusTmCreator::builder()
|
||||
.with_apid(u11::new(0x123))
|
||||
.with_sequence_count(u14::new(0x234))
|
||||
.with_service(17)
|
||||
.with_subservice(2)
|
||||
.with_service_type_id(17)
|
||||
.with_message_subtype_id(2)
|
||||
.with_timestamp(timestamp)
|
||||
.build();
|
||||
}
|
||||
PusTmBuilder::new()
|
||||
.with_apid(u11::new(0x123))
|
||||
.with_sequence_count(u14::new(0x234))
|
||||
.with_service(17)
|
||||
.with_subservice(2)
|
||||
.with_service_type_id(17)
|
||||
.with_message_subtype_id(2)
|
||||
.with_timestamp(timestamp)
|
||||
.build()
|
||||
}
|
||||
|
||||
fn base_ping_reply_full_ctor_no_checksum<'a, 'b>(timestamp: &'a [u8]) -> PusTmCreator<'a, 'b> {
|
||||
let sph = SpHeader::new_for_unseg_tm(u11::new(0x123), u14::new(0x234), 0);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(MessageTypeId::new(17, 2), timestamp);
|
||||
PusTmCreator::new_no_source_data(
|
||||
sph,
|
||||
tm_header,
|
||||
@@ -1407,13 +1543,13 @@ mod tests {
|
||||
}
|
||||
fn ping_reply_with_data<'a, 'b>(timestamp: &'a [u8]) -> PusTmCreator<'a, 'b> {
|
||||
let sph = SpHeader::new_for_unseg_tm(u11::new(0x123), u14::new(0x234), 0);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(MessageTypeId::new(17, 2), timestamp);
|
||||
PusTmCreator::new(sph, tm_header, DUMMY_DATA, CreatorConfig::default())
|
||||
}
|
||||
|
||||
fn base_hk_reply<'a, 'b>(timestamp: &'a [u8], src_data: &'b [u8]) -> PusTmCreator<'a, 'b> {
|
||||
let sph = SpHeader::new_for_unseg_tm(u11::new(0x123), u14::new(0x234), 0);
|
||||
let tc_header = PusTmSecondaryHeader::new_simple(3, 5, timestamp);
|
||||
let tc_header = PusTmSecondaryHeader::new_simple(MessageTypeId::new(3, 5), timestamp);
|
||||
PusTmCreator::new(sph, tc_header, src_data, CreatorConfig::default())
|
||||
}
|
||||
|
||||
@@ -1422,7 +1558,7 @@ mod tests {
|
||||
src_data: &'b [u8],
|
||||
) -> PusTmCreator<'a, 'b> {
|
||||
let sph = SpHeader::new_for_unseg_tm(u11::new(0x123), u14::new(0x234), 0);
|
||||
let tc_header = PusTmSecondaryHeader::new_simple(3, 5, timestamp);
|
||||
let tc_header = PusTmSecondaryHeader::new_simple(MessageTypeId::new(3, 5), timestamp);
|
||||
PusTmCreator::new(
|
||||
sph,
|
||||
tc_header,
|
||||
@@ -1459,8 +1595,7 @@ mod tests {
|
||||
let mut stamp_buf: [u8; 8] = [0; 8];
|
||||
let pus_tm = PusTmCreator::new_simple(
|
||||
sph,
|
||||
17,
|
||||
2,
|
||||
MessageTypeId::new(17, 2),
|
||||
&time_provider,
|
||||
&mut stamp_buf,
|
||||
&[],
|
||||
@@ -1486,7 +1621,7 @@ mod tests {
|
||||
fn test_serialization_no_source_data_alt_ctor() {
|
||||
let timestamp = dummy_timestamp();
|
||||
let sph = SpHeader::new_for_unseg_tm(u11::new(0x123), u14::new(0x234), 0);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(MessageTypeId::new(17, 2), timestamp);
|
||||
let mut buf: [u8; 32] = [0; 32];
|
||||
let mut pus_tm =
|
||||
PusTmCreatorWithReservedSourceData::new(&mut buf, sph, tm_header, 0, true).unwrap();
|
||||
@@ -1502,7 +1637,7 @@ mod tests {
|
||||
fn test_serialization_no_source_data_alt_ctor_no_checksum_verification() {
|
||||
let timestamp = dummy_timestamp();
|
||||
let sph = SpHeader::new_for_unseg_tm(u11::new(0x123), u14::new(0x234), 0);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(MessageTypeId::new(17, 2), timestamp);
|
||||
let mut buf: [u8; 32] = [0; 32];
|
||||
let mut pus_tm =
|
||||
PusTmCreatorWithReservedSourceData::new(&mut buf, sph, tm_header, 0, true).unwrap();
|
||||
@@ -1520,7 +1655,7 @@ mod tests {
|
||||
fn test_serialization_no_source_data_alt_ctor_no_checksum() {
|
||||
let timestamp = dummy_timestamp();
|
||||
let sph = SpHeader::new_for_unseg_tm(u11::new(0x123), u14::new(0x234), 0);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(MessageTypeId::new(17, 2), timestamp);
|
||||
let mut buf: [u8; 32] = [0; 32];
|
||||
let mut pus_tm =
|
||||
PusTmCreatorWithReservedSourceData::new(&mut buf, sph, tm_header, 0, false).unwrap();
|
||||
@@ -1596,7 +1731,8 @@ mod tests {
|
||||
let src_data = &[1, 2, 3];
|
||||
let mut buf: [u8; 32] = [0; 32];
|
||||
let sph = SpHeader::new_for_unseg_tm(u11::new(0x123), u14::new(0x234), 0);
|
||||
let tc_header = PusTmSecondaryHeader::new_simple(3, 5, dummy_timestamp());
|
||||
let tc_header =
|
||||
PusTmSecondaryHeader::new_simple(MessageTypeId::new(3, 5), dummy_timestamp());
|
||||
let mut hk_reply_unwritten =
|
||||
PusTmCreatorWithReservedSourceData::new(&mut buf, sph, tc_header, 3, true).unwrap();
|
||||
assert_eq!(hk_reply_unwritten.source_data_len(), 3);
|
||||
@@ -1616,7 +1752,8 @@ mod tests {
|
||||
let src_data = &[1, 2, 3];
|
||||
let mut buf: [u8; 32] = [0; 32];
|
||||
let sph = SpHeader::new_for_unseg_tm(u11::new(0x123), u14::new(0x234), 0);
|
||||
let tc_header = PusTmSecondaryHeader::new_simple(3, 5, dummy_timestamp());
|
||||
let tc_header =
|
||||
PusTmSecondaryHeader::new_simple(MessageTypeId::new(3, 5), dummy_timestamp());
|
||||
let mut hk_reply_unwritten =
|
||||
PusTmCreatorWithReservedSourceData::new(&mut buf, sph, tc_header, 3, true).unwrap();
|
||||
assert_eq!(hk_reply_unwritten.source_data_len(), 3);
|
||||
@@ -1640,7 +1777,7 @@ mod tests {
|
||||
pus_tm.set_msg_counter(0x1f1f);
|
||||
assert_eq!(pus_tm.sc_time_ref_status().value(), 0b1010);
|
||||
assert_eq!(pus_tm.dest_id(), 0x7fff);
|
||||
assert_eq!(pus_tm.msg_counter(), 0x1f1f);
|
||||
assert_eq!(pus_tm.msg_type_counter(), 0x1f1f);
|
||||
pus_tm.set_apid(u11::new(0x7ff));
|
||||
assert_eq!(pus_tm.apid().value(), 0x7ff);
|
||||
}
|
||||
@@ -1772,7 +1909,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_manual_field_update() {
|
||||
let sph = SpHeader::new_for_unseg_tm(u11::new(0x123), u14::new(0x234), 0);
|
||||
let tc_header = PusTmSecondaryHeader::new_simple(17, 2, dummy_timestamp());
|
||||
let tc_header =
|
||||
PusTmSecondaryHeader::new_simple(MessageTypeId::new(17, 2), dummy_timestamp());
|
||||
let mut tm = PusTmCreator::new_no_source_data(
|
||||
sph,
|
||||
tc_header,
|
||||
@@ -1928,10 +2066,10 @@ mod tests {
|
||||
exp_full_len: usize,
|
||||
) {
|
||||
assert!(tm.is_tm());
|
||||
assert_eq!(PusPacket::service(tm), 17);
|
||||
assert_eq!(GenericPusTmSecondaryHeader::service(tm), 17);
|
||||
assert_eq!(PusPacket::subservice(tm), 2);
|
||||
assert_eq!(GenericPusTmSecondaryHeader::subservice(tm), 2);
|
||||
assert_eq!(PusPacket::service_type_id(tm), 17);
|
||||
assert_eq!(GenericPusTmSecondaryHeader::service_type_id(tm), 17);
|
||||
assert_eq!(PusPacket::message_subtype_id(tm), 2);
|
||||
assert_eq!(GenericPusTmSecondaryHeader::message_subtype_id(tm), 2);
|
||||
assert!(tm.sec_header_flag());
|
||||
if has_user_data {
|
||||
assert!(!tm.user_data().is_empty());
|
||||
@@ -1946,7 +2084,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(tm.data_len(), exp_full_len as u16 - 7);
|
||||
assert_eq!(tm.dest_id(), 0x0000);
|
||||
assert_eq!(tm.msg_counter(), 0x0000);
|
||||
assert_eq!(tm.msg_type_counter(), 0x0000);
|
||||
assert_eq!(tm.sc_time_ref_status().value(), 0b0000);
|
||||
}
|
||||
|
||||
@@ -1984,7 +2122,7 @@ mod tests {
|
||||
// This performs all necessary checks, including the CRC check.
|
||||
let tm_read_back = PusTmReader::new(&buf, 7).expect("Re-creating PUS TM failed");
|
||||
assert_eq!(tm_read_back.packet_len(), tm_size);
|
||||
assert_eq!(tm_read_back.msg_counter(), 100);
|
||||
assert_eq!(tm_read_back.msg_type_counter(), 100);
|
||||
assert_eq!(tm_read_back.dest_id(), 55);
|
||||
assert_eq!(tm_read_back.seq_count(), MAX_SEQ_COUNT);
|
||||
assert_eq!(tm_read_back.apid(), MAX_APID);
|
||||
@@ -2003,8 +2141,8 @@ mod tests {
|
||||
writer.set_msg_count(100);
|
||||
writer.set_seq_count(MAX_SEQ_COUNT);
|
||||
writer.set_apid(MAX_APID);
|
||||
assert_eq!(PusPacket::service(&writer), 17);
|
||||
assert_eq!(PusPacket::subservice(&writer), 2);
|
||||
assert_eq!(PusPacket::service_type_id(&writer), 17);
|
||||
assert_eq!(PusPacket::message_subtype_id(&writer), 2);
|
||||
assert_eq!(writer.apid(), MAX_APID);
|
||||
assert_eq!(writer.seq_count(), MAX_SEQ_COUNT);
|
||||
}
|
||||
@@ -2023,12 +2161,15 @@ mod tests {
|
||||
writer.set_msg_count(100);
|
||||
writer.set_seq_count(MAX_SEQ_COUNT);
|
||||
writer.set_apid(MAX_APID);
|
||||
assert_eq!(PusPacket::service(&writer), 17);
|
||||
assert_eq!(PusPacket::subservice(&writer), 2);
|
||||
assert_eq!(PusPacket::service_type_id(&writer), 17);
|
||||
assert_eq!(PusPacket::message_subtype_id(&writer), 2);
|
||||
assert_eq!(writer.dest_id(), 55);
|
||||
assert_eq!(writer.msg_counter(), 100);
|
||||
assert_eq!(writer.msg_type_counter(), 100);
|
||||
assert_eq!(writer.sec_header_without_timestamp().dest_id(), 55);
|
||||
assert_eq!(writer.sec_header_without_timestamp().msg_counter(), 100);
|
||||
assert_eq!(
|
||||
writer.sec_header_without_timestamp().msg_type_counter(),
|
||||
100
|
||||
);
|
||||
assert_eq!(writer.user_data(), DUMMY_DATA);
|
||||
// Need to check crc16 before finish, because finish will update the CRC.
|
||||
let crc16 = writer.checksum();
|
||||
@@ -2039,7 +2180,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_sec_header_without_stamp() {
|
||||
let sec_header = PusTmSecondaryHeader::new_simple_no_timestamp(17, 1);
|
||||
let sec_header = PusTmSecondaryHeader::new_simple_no_timestamp(MessageTypeId::new(17, 1));
|
||||
assert_eq!(sec_header.timestamp, &[]);
|
||||
}
|
||||
|
||||
@@ -2105,8 +2246,7 @@ mod tests {
|
||||
let mut stamp_buf: [u8; 8] = [0; 8];
|
||||
let pus_tm = PusTmCreator::new_simple(
|
||||
sph,
|
||||
17,
|
||||
2,
|
||||
MessageTypeId::new(17, 2),
|
||||
&time_provider,
|
||||
&mut stamp_buf,
|
||||
&[],
|
||||
@@ -2127,8 +2267,7 @@ mod tests {
|
||||
let mut stamp_buf: [u8; 8] = [0; 8];
|
||||
let pus_tm = PusTmCreator::new_simple(
|
||||
sph,
|
||||
17,
|
||||
2,
|
||||
MessageTypeId::new(17, 2),
|
||||
&time_provider,
|
||||
&mut stamp_buf,
|
||||
&[],
|
||||
@@ -2166,8 +2305,8 @@ mod tests {
|
||||
SequenceFlags::Unsegmented,
|
||||
u14::new(0x34),
|
||||
))
|
||||
.with_service(17)
|
||||
.with_subservice(2)
|
||||
.with_service_type_id(17)
|
||||
.with_message_subtype_id(2)
|
||||
.with_dest_id(0x2f2f)
|
||||
.with_checksum(false)
|
||||
.build();
|
||||
@@ -2175,7 +2314,7 @@ mod tests {
|
||||
assert_eq!(tm.sequence_flags(), SequenceFlags::Unsegmented);
|
||||
assert_eq!(tm.apid().value(), 0x02);
|
||||
assert_eq!(tm.packet_type(), PacketType::Tm);
|
||||
assert_eq!(tm.service(), 17);
|
||||
assert_eq!(tm.subservice(), 2);
|
||||
assert_eq!(tm.service_type_id(), 17);
|
||||
assert_eq!(tm.message_subtype_id(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,8 +27,8 @@
|
||||
//! true
|
||||
//! );
|
||||
//! println!("{:?}", ping_tm);
|
||||
//! assert_eq!(ping_tm.service(), 17);
|
||||
//! assert_eq!(ping_tm.subservice(), 2);
|
||||
//! assert_eq!(ping_tm.service_type_id(), 17);
|
||||
//! assert_eq!(ping_tm.message_subtype_id(), 2);
|
||||
//! assert_eq!(ping_tm.apid().value(), 0x02);
|
||||
//!
|
||||
//! // Serialize TM into a raw buffer
|
||||
@@ -42,16 +42,17 @@
|
||||
//! // Deserialize from the raw byte representation
|
||||
//! let ping_tm_reader = PusTmReader::new(&test_buf, &SecondaryHeaderParameters::new_minimal(7)).expect("deserialization failed");
|
||||
//! assert_eq!(written_size, ping_tm_reader.packet_len());
|
||||
//! assert_eq!(ping_tm_reader.service(), 17);
|
||||
//! assert_eq!(ping_tm_reader.subservice(), 2);
|
||||
//! assert_eq!(ping_tm_reader.service_type_id(), 17);
|
||||
//! assert_eq!(ping_tm_reader.message_subtype_id(), 2);
|
||||
//! assert_eq!(ping_tm_reader.apid().value(), 0x02);
|
||||
//! assert_eq!(ping_tm_reader.timestamp(), &time_buf);
|
||||
//! ```
|
||||
use crate::crc::{CRC_CCITT_FALSE, CRC_CCITT_FALSE_NO_TABLE};
|
||||
use crate::ecss::tm::IsPusTelemetry;
|
||||
use crate::ecss::{
|
||||
calc_pus_crc16, crc_from_raw_data, sp_header_impls, user_data_from_raw,
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error, CrcType, PusError, PusPacket, PusVersion,
|
||||
WritablePusPacket,
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error, CrcType, MessageTypeId, PusError, PusPacket,
|
||||
PusVersion, WritablePusPacket,
|
||||
};
|
||||
use crate::util::{UnsignedByteField, UnsignedEnum};
|
||||
use crate::{
|
||||
@@ -73,55 +74,78 @@ use crate::time::{TimeWriter, TimestampError};
|
||||
|
||||
use super::verify_crc16_ccitt_false_from_raw_to_pus_error_no_table;
|
||||
|
||||
pub trait IsPusTelemetry {}
|
||||
|
||||
/// Length without timestamp
|
||||
pub const PUS_TM_MIN_SEC_HEADER_LEN: usize = 3;
|
||||
/// Minimal length of a PUS TM packet without source data.
|
||||
pub const PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA: usize =
|
||||
CCSDS_HEADER_LEN + PUS_TM_MIN_SEC_HEADER_LEN + size_of::<CrcType>();
|
||||
|
||||
/// Generic properties of a PUS-A PUS TM secondary header.
|
||||
pub trait GenericPusTmSecondaryHeader {
|
||||
/// PUS version field.
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
/// Service field.
|
||||
fn service(&self) -> u8;
|
||||
/// Subservice field.
|
||||
fn subservice(&self) -> u8;
|
||||
/// Message counter field for the service ID.
|
||||
fn msg_counter(&self) -> Option<u8>;
|
||||
/// Destination ID.
|
||||
fn dest_id(&self) -> Option<UnsignedByteField>;
|
||||
/// Number of spare bytes.
|
||||
fn spare_bytes(&self) -> usize;
|
||||
}
|
||||
|
||||
/// Managed parameters for the secondary header which can not be deduced from the packet itself.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
pub struct SecondaryHeaderParameters {
|
||||
/// Timestamp length in bytes.
|
||||
pub timestamp_len: usize,
|
||||
/// Does the packet have a message counter?
|
||||
pub has_msg_counter: bool,
|
||||
pub dest_id_len: Option<usize>,
|
||||
/// Present and length of the destination ID.
|
||||
pub opt_dest_id_len: Option<usize>,
|
||||
/// Number of spare bytes.
|
||||
pub spare_bytes: usize,
|
||||
}
|
||||
|
||||
impl SecondaryHeaderParameters {
|
||||
/// Minimal constructor.
|
||||
pub const fn new_minimal(timestamp_len: usize) -> Self {
|
||||
Self {
|
||||
timestamp_len,
|
||||
has_msg_counter: false,
|
||||
dest_id_len: None,
|
||||
opt_dest_id_len: None,
|
||||
spare_bytes: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PUS TM secondary header.
|
||||
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PusTmSecondaryHeader<'stamp> {
|
||||
pus_version: PusVersion,
|
||||
/// Service field.
|
||||
pub service: u8,
|
||||
/// Subservice field.
|
||||
pub subservice: u8,
|
||||
/// Service message counter.
|
||||
pub msg_counter: Option<u8>,
|
||||
/// Destination ID field.
|
||||
pub dest_id: Option<UnsignedByteField>,
|
||||
/// Timestamp slice.
|
||||
pub timestamp: &'stamp [u8],
|
||||
/// Number of spare bytes to add after the timestamp.
|
||||
pub spare_bytes: usize,
|
||||
}
|
||||
|
||||
impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
/// Simple constructor.
|
||||
///
|
||||
/// Allows setting the service, subservice and timestamp and sets default values for the
|
||||
/// other fields.
|
||||
#[inline]
|
||||
pub fn new_simple(service: u8, subservice: u8, timestamp: &'stamp [u8]) -> Self {
|
||||
Self::new(service, subservice, None, None, timestamp, 0)
|
||||
@@ -133,6 +157,7 @@ impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
Self::new(service, subservice, None, None, &[], 0)
|
||||
}
|
||||
|
||||
/// Generic constructor.
|
||||
#[inline]
|
||||
pub fn new(
|
||||
service: u8,
|
||||
@@ -153,6 +178,7 @@ impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct the secondary header from a raw byte slice.
|
||||
pub fn from_bytes(
|
||||
buf: &'stamp [u8],
|
||||
params: &SecondaryHeaderParameters,
|
||||
@@ -180,7 +206,7 @@ impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
current_idx += 1;
|
||||
}
|
||||
let mut dest_id = None;
|
||||
if let Some(dest_id_len) = params.dest_id_len {
|
||||
if let Some(dest_id_len) = params.opt_dest_id_len {
|
||||
dest_id = Some(
|
||||
UnsignedByteField::new_from_be_bytes(
|
||||
dest_id_len,
|
||||
@@ -201,6 +227,7 @@ impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Write the PUS TM secondary header to a provided buffer.
|
||||
pub fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
let written_len = self.written_len();
|
||||
if buf.len() < written_len {
|
||||
@@ -229,6 +256,7 @@ impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
Ok(written_len)
|
||||
}
|
||||
|
||||
/// Convert the PUS TM packet secondary header to a [alloc::vec::Vec].
|
||||
#[cfg(feature = "alloc")]
|
||||
pub fn to_vec(&self) -> Vec<u8> {
|
||||
let mut vec = alloc::vec![0; self.written_len()];
|
||||
@@ -236,6 +264,7 @@ impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
vec
|
||||
}
|
||||
|
||||
/// Length of the secondary header when written to bytes.
|
||||
pub fn written_len(&self) -> usize {
|
||||
let mut len = PUS_TM_MIN_SEC_HEADER_LEN + self.timestamp.len() + self.spare_bytes;
|
||||
if let Some(dest_id) = self.dest_id {
|
||||
@@ -247,9 +276,10 @@ impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
len
|
||||
}
|
||||
|
||||
/// Length for the provided packet parameters.
|
||||
pub fn len_for_params(params: &SecondaryHeaderParameters) -> usize {
|
||||
let mut len = PUS_TM_MIN_SEC_HEADER_LEN + params.timestamp_len + params.spare_bytes;
|
||||
if let Some(dest_id) = params.dest_id_len {
|
||||
if let Some(dest_id) = params.opt_dest_id_len {
|
||||
len += dest_id;
|
||||
}
|
||||
if params.has_msg_counter {
|
||||
@@ -308,7 +338,9 @@ impl GenericPusTmSecondaryHeader for PusTmSecondaryHeader<'_> {
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PusTmCreator<'time, 'src_data> {
|
||||
/// Space packet header.
|
||||
pub sp_header: SpHeader,
|
||||
/// PUS TM secondary header.
|
||||
#[cfg_attr(feature = "serde", serde(borrow))]
|
||||
pub sec_header: PusTmSecondaryHeader<'time>,
|
||||
source_data: &'src_data [u8],
|
||||
@@ -351,6 +383,8 @@ impl<'time, 'src_data> PusTmCreator<'time, 'src_data> {
|
||||
pus_tm
|
||||
}
|
||||
|
||||
/// Simple constructor which builds the [PusTmSecondaryHeader] internally from the
|
||||
/// provided arguments.
|
||||
#[inline]
|
||||
pub fn new_simple(
|
||||
sp_header: SpHeader,
|
||||
@@ -367,6 +401,7 @@ impl<'time, 'src_data> PusTmCreator<'time, 'src_data> {
|
||||
Ok(Self::new(sp_header, sec_header, source_data, set_ccsds_len))
|
||||
}
|
||||
|
||||
/// Constructor for PUS TM packets without source data.
|
||||
#[inline]
|
||||
pub fn new_no_source_data(
|
||||
sp_header: SpHeader,
|
||||
@@ -376,21 +411,25 @@ impl<'time, 'src_data> PusTmCreator<'time, 'src_data> {
|
||||
Self::new(sp_header, sec_header, &[], set_ccsds_len)
|
||||
}
|
||||
|
||||
/// Raw timestamp slice.
|
||||
#[inline]
|
||||
pub fn timestamp(&self) -> &[u8] {
|
||||
self.sec_header.timestamp
|
||||
}
|
||||
|
||||
/// Raw source data slice.
|
||||
#[inline]
|
||||
pub fn source_data(&self) -> &[u8] {
|
||||
self.source_data
|
||||
}
|
||||
|
||||
/// Set the destination ID.
|
||||
#[inline]
|
||||
pub fn set_dest_id(&mut self, dest_id: Option<UnsignedByteField>) {
|
||||
self.sec_header.dest_id = dest_id;
|
||||
}
|
||||
|
||||
/// Set the message counter for the current service ID.
|
||||
#[inline]
|
||||
pub fn set_msg_counter(&mut self, msg_counter: Option<u8>) {
|
||||
self.sec_header.msg_counter = msg_counter
|
||||
@@ -559,12 +598,22 @@ impl PusPacket for PusTmCreator<'_, '_> {
|
||||
Ok(self.sec_header.pus_version)
|
||||
}
|
||||
|
||||
delegate!(to self.sec_header {
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
});
|
||||
#[inline]
|
||||
fn message_type_id(&self) -> super::MessageTypeId {
|
||||
super::MessageTypeId {
|
||||
type_id: self.sec_header.service,
|
||||
subtype_id: self.sec_header.subservice,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.sec_header.service
|
||||
}
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.sec_header.subservice
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn user_data(&self) -> &[u8] {
|
||||
@@ -665,6 +714,7 @@ impl<'buf> PusTmCreatorWithReservedSourceData<'buf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Length of the full packet when written to bytes.
|
||||
#[inline]
|
||||
pub const fn len_written(&self) -> usize {
|
||||
self.full_len
|
||||
@@ -682,6 +732,7 @@ impl<'buf> PusTmCreatorWithReservedSourceData<'buf> {
|
||||
&self.buf[self.source_data_offset..self.full_len - 2]
|
||||
}
|
||||
|
||||
/// Source data length.
|
||||
#[inline]
|
||||
pub fn source_data_len(&self) -> usize {
|
||||
self.full_len - 2 - self.source_data_offset
|
||||
@@ -735,7 +786,9 @@ impl<'buf> PusTmCreatorWithReservedSourceData<'buf> {
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PusTmReader<'raw_data> {
|
||||
/// Space packet header.
|
||||
pub sp_header: SpHeader,
|
||||
/// PUS TM secondary header.
|
||||
pub sec_header: PusTmSecondaryHeader<'raw_data>,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
raw_data: &'raw_data [u8],
|
||||
@@ -769,6 +822,7 @@ impl<'raw_data> PusTmReader<'raw_data> {
|
||||
Ok(tc)
|
||||
}
|
||||
|
||||
/// New constructor which does not check the CRC16.
|
||||
pub fn new_no_crc_check(
|
||||
slice: &'raw_data [u8],
|
||||
sec_header_params: &SecondaryHeaderParameters,
|
||||
@@ -812,21 +866,25 @@ impl<'raw_data> PusTmReader<'raw_data> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Length of the full packet as packed in the raw data.
|
||||
#[inline]
|
||||
pub fn len_packed(&self) -> usize {
|
||||
self.sp_header.packet_len()
|
||||
}
|
||||
|
||||
/// Raw source data slice.
|
||||
#[inline]
|
||||
pub fn source_data(&self) -> &[u8] {
|
||||
self.user_data()
|
||||
}
|
||||
|
||||
/// Raw timestamp slice.
|
||||
#[inline]
|
||||
pub fn timestamp(&self) -> &[u8] {
|
||||
self.sec_header.timestamp
|
||||
}
|
||||
|
||||
/// CRC16 checksum of the packet.
|
||||
#[inline]
|
||||
pub fn crc16(&self) -> u16 {
|
||||
self.crc16
|
||||
@@ -867,12 +925,23 @@ impl PusPacket for PusTmReader<'_> {
|
||||
Ok(self.sec_header.pus_version)
|
||||
}
|
||||
|
||||
delegate!(to self.sec_header {
|
||||
#[inline]
|
||||
fn service(&self) -> u8;
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8;
|
||||
});
|
||||
#[inline]
|
||||
fn message_type_id(&self) -> super::MessageTypeId {
|
||||
MessageTypeId {
|
||||
type_id: self.sec_header.service,
|
||||
subtype_id: self.sec_header.subservice,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.sec_header.service
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.sec_header.subservice
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn user_data(&self) -> &[u8] {
|
||||
@@ -920,16 +989,21 @@ impl PartialEq<PusTmReader<'_>> for PusTmCreator<'_, '_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Secondary header field not present error.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("this field is not present in the secondary header")]
|
||||
pub struct SecondaryHeaderFieldNotPresentError;
|
||||
|
||||
/// Destination ID operation error.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DestIdOperationError {
|
||||
/// Field is not present in the secondary header.
|
||||
#[error("this field is not present in the secondary header")]
|
||||
FieldNotPresent(#[from] SecondaryHeaderFieldNotPresentError),
|
||||
/// Invalid field length.
|
||||
#[error("invalid byte field length")]
|
||||
InvalidFieldLen,
|
||||
/// Bzyte conversion error.
|
||||
#[error("byte conversion error")]
|
||||
ByteConversionError(#[from] ByteConversionError),
|
||||
}
|
||||
@@ -987,15 +1061,16 @@ impl<'raw> PusTmZeroCopyWriter<'raw> {
|
||||
self.raw_tm[0..2].copy_from_slice(&updated_apid.to_be_bytes());
|
||||
}
|
||||
|
||||
/// Destination ID field if present.
|
||||
pub fn dest_id(&self) -> Result<Option<UnsignedByteField>, ByteConversionError> {
|
||||
if self.sec_header_params.dest_id_len.is_none() {
|
||||
if self.sec_header_params.opt_dest_id_len.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut base_idx = 10;
|
||||
if self.sec_header_params.has_msg_counter {
|
||||
base_idx += 1;
|
||||
}
|
||||
let dest_id_len = self.sec_header_params.dest_id_len.unwrap();
|
||||
let dest_id_len = self.sec_header_params.opt_dest_id_len.unwrap();
|
||||
if self.raw_tm.len() < base_idx + dest_id_len {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: self.raw_tm.len(),
|
||||
@@ -1011,6 +1086,7 @@ impl<'raw> PusTmZeroCopyWriter<'raw> {
|
||||
))
|
||||
}
|
||||
|
||||
/// Message counter if present.
|
||||
pub fn msg_counter(&self) -> Option<u8> {
|
||||
if !self.sec_header_params.has_msg_counter {
|
||||
return None;
|
||||
@@ -1040,10 +1116,10 @@ impl<'raw> PusTmZeroCopyWriter<'raw> {
|
||||
&mut self,
|
||||
dest_id: UnsignedByteField,
|
||||
) -> Result<(), DestIdOperationError> {
|
||||
if self.sec_header_params.dest_id_len.is_none() {
|
||||
if self.sec_header_params.opt_dest_id_len.is_none() {
|
||||
return Err(SecondaryHeaderFieldNotPresentError.into());
|
||||
}
|
||||
let dest_id_len = self.sec_header_params.dest_id_len.unwrap();
|
||||
let dest_id_len = self.sec_header_params.opt_dest_id_len.unwrap();
|
||||
if dest_id.size() != dest_id_len {
|
||||
return Err(DestIdOperationError::InvalidFieldLen);
|
||||
}
|
||||
@@ -1072,6 +1148,7 @@ impl<'raw> PusTmZeroCopyWriter<'raw> {
|
||||
crate::zc::SpHeader::read_from_bytes(&self.raw_tm[0..CCSDS_HEADER_LEN]).unwrap()
|
||||
}
|
||||
|
||||
/// Set the sequence count.
|
||||
#[inline]
|
||||
pub fn set_seq_count(&mut self, seq_count: u14) {
|
||||
let new_psc = (u16::from_be_bytes(self.raw_tm[2..4].try_into().unwrap()) & 0xC000)
|
||||
@@ -1117,12 +1194,20 @@ impl PusPacket for PusTmZeroCopyWriter<'_> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service(&self) -> u8 {
|
||||
fn message_type_id(&self) -> super::MessageTypeId {
|
||||
MessageTypeId {
|
||||
type_id: self.service_type_id(),
|
||||
subtype_id: self.message_subtype_id(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service_type_id(&self) -> u8 {
|
||||
self.raw_tm[7]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8 {
|
||||
fn message_subtype_id(&self) -> u8 {
|
||||
self.raw_tm[8]
|
||||
}
|
||||
|
||||
@@ -1494,7 +1579,7 @@ mod tests {
|
||||
&SecondaryHeaderParameters {
|
||||
timestamp_len: 7,
|
||||
has_msg_counter: msg_counter.is_some(),
|
||||
dest_id_len: dest_id.as_ref().map(|id| id.size()),
|
||||
opt_dest_id_len: dest_id.as_ref().map(|id| id.size()),
|
||||
spare_bytes: 0,
|
||||
},
|
||||
)
|
||||
@@ -1774,9 +1859,9 @@ mod tests {
|
||||
msg_counter: Option<u8>,
|
||||
) {
|
||||
assert!(tm.is_tm());
|
||||
assert_eq!(PusPacket::service(tm), 17);
|
||||
assert_eq!(PusPacket::service_type_id(tm), 17);
|
||||
assert_eq!(GenericPusTmSecondaryHeader::service(tm), 17);
|
||||
assert_eq!(PusPacket::subservice(tm), 2);
|
||||
assert_eq!(PusPacket::message_subtype_id(tm), 2);
|
||||
assert_eq!(GenericPusTmSecondaryHeader::subservice(tm), 2);
|
||||
assert!(tm.sec_header_flag());
|
||||
if has_user_data {
|
||||
@@ -1849,7 +1934,7 @@ mod tests {
|
||||
&SecondaryHeaderParameters {
|
||||
timestamp_len: dummy_timestamp().len(),
|
||||
has_msg_counter: false,
|
||||
dest_id_len: Some(2),
|
||||
opt_dest_id_len: Some(2),
|
||||
spare_bytes: 0,
|
||||
},
|
||||
)
|
||||
@@ -1859,8 +1944,8 @@ mod tests {
|
||||
writer
|
||||
.set_destination_id(UnsignedByteFieldU16::new(0xf1f1).into())
|
||||
.unwrap();
|
||||
assert_eq!(PusPacket::service(&writer), 17);
|
||||
assert_eq!(PusPacket::subservice(&writer), 2);
|
||||
assert_eq!(PusPacket::service_type_id(&writer), 17);
|
||||
assert_eq!(PusPacket::message_subtype_id(&writer), 2);
|
||||
assert_eq!(
|
||||
writer.dest_id().unwrap().unwrap(),
|
||||
UnsignedByteFieldU16::new(0xf1f1).into()
|
||||
@@ -1881,8 +1966,8 @@ mod tests {
|
||||
.expect("Creating zero copy writer failed");
|
||||
writer.set_seq_count(MAX_SEQ_COUNT);
|
||||
writer.set_apid(MAX_APID);
|
||||
assert_eq!(PusPacket::service(&writer), 17);
|
||||
assert_eq!(PusPacket::subservice(&writer), 2);
|
||||
assert_eq!(PusPacket::service_type_id(&writer), 17);
|
||||
assert_eq!(PusPacket::message_subtype_id(&writer), 2);
|
||||
assert!(writer.dest_id().unwrap().is_none());
|
||||
assert!(writer.msg_counter().is_none());
|
||||
if let Err(err) = writer.set_destination_id(UnsignedByteFieldU16::new(0xf1f1).into()) {
|
||||
|
||||
@@ -3,18 +3,27 @@ use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Message subtype ID.
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum Subservice {
|
||||
pub enum MessageSubtypeId {
|
||||
/// Telemetry - Acceptance success.
|
||||
TmAcceptanceSuccess = 1,
|
||||
/// Telemetry - Acceptance failure.
|
||||
TmAcceptanceFailure = 2,
|
||||
/// Telemetry - Start success.
|
||||
TmStartSuccess = 3,
|
||||
/// Telemetry - Start failure.
|
||||
TmStartFailure = 4,
|
||||
/// Telemetry - Step success.
|
||||
TmStepSuccess = 5,
|
||||
/// Telemetry - Step failure.
|
||||
TmStepFailure = 6,
|
||||
/// Telemetry - Completion success.
|
||||
TmCompletionSuccess = 7,
|
||||
/// Telemetry - Completion failure.
|
||||
TmCompletionFailure = 8,
|
||||
}
|
||||
|
||||
@@ -24,13 +33,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_conv_into_u8() {
|
||||
let subservice: u8 = Subservice::TmCompletionSuccess.into();
|
||||
let subservice: u8 = MessageSubtypeId::TmCompletionSuccess.into();
|
||||
assert_eq!(subservice, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_conv_from_u8() {
|
||||
let subservice: Subservice = 7.try_into().unwrap();
|
||||
assert_eq!(subservice, Subservice::TmCompletionSuccess);
|
||||
let subservice: MessageSubtypeId = 7.try_into().unwrap();
|
||||
assert_eq!(subservice, MessageSubtypeId::TmCompletionSuccess);
|
||||
}
|
||||
}
|
||||
|
||||
1798
src/lib.rs
1798
src/lib.rs
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,8 @@
|
||||
//! # Sequence counter module.
|
||||
//!
|
||||
//! CCSDS and ECSS packet standard oftentimes use sequence counters, for example to allow detecting
|
||||
//! packet gaps. This module provides basic abstractions and helper components to implement
|
||||
//! sequence counters.
|
||||
use crate::MAX_SEQ_COUNT;
|
||||
use arbitrary_int::traits::Integer;
|
||||
use core::cell::Cell;
|
||||
@@ -9,28 +14,37 @@ use paste::paste;
|
||||
/// static structs when using the interior mutability pattern. This can be achieved by using
|
||||
/// [Cell], [core::cell::RefCell] or atomic types.
|
||||
pub trait SequenceCounter {
|
||||
/// Raw type of the counter.
|
||||
type Raw: Into<u64>;
|
||||
|
||||
/// Bit width of the counter.
|
||||
const MAX_BIT_WIDTH: usize;
|
||||
|
||||
/// Get the current sequence count value.
|
||||
fn get(&self) -> Self::Raw;
|
||||
|
||||
/// Increment the sequence count by one.
|
||||
fn increment(&self);
|
||||
|
||||
/// Increment the sequence count by one, mutable API.
|
||||
fn increment_mut(&mut self) {
|
||||
self.increment();
|
||||
}
|
||||
|
||||
/// Get the current sequence count value and increment the counter by one.
|
||||
fn get_and_increment(&self) -> Self::Raw {
|
||||
let val = self.get();
|
||||
self.increment();
|
||||
val
|
||||
}
|
||||
|
||||
/// Get the current sequence count value and increment the counter by one, mutable API.
|
||||
fn get_and_increment_mut(&mut self) -> Self::Raw {
|
||||
self.get_and_increment()
|
||||
}
|
||||
}
|
||||
|
||||
/// Simple sequence counter which wraps at ´T::MAX´.
|
||||
#[derive(Clone)]
|
||||
pub struct SequenceCounterSimple<T: Copy> {
|
||||
seq_count: Cell<T>,
|
||||
@@ -43,12 +57,15 @@ macro_rules! impl_for_primitives {
|
||||
$(
|
||||
paste! {
|
||||
impl SequenceCounterSimple<$ty> {
|
||||
/// Constructor with a custom maximum value.
|
||||
pub fn [<new_custom_max_val_ $ty>](max_val: $ty) -> Self {
|
||||
Self {
|
||||
seq_count: Cell::new(0),
|
||||
max_val,
|
||||
}
|
||||
}
|
||||
|
||||
/// Generic constructor.
|
||||
pub fn [<new_ $ty>]() -> Self {
|
||||
Self {
|
||||
seq_count: Cell::new(0),
|
||||
@@ -119,6 +136,7 @@ impl SequenceCounter for SequenceCounterCcsdsSimple {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_has_atomic = "8")]
|
||||
impl SequenceCounter for core::sync::atomic::AtomicU8 {
|
||||
type Raw = u8;
|
||||
|
||||
@@ -133,6 +151,7 @@ impl SequenceCounter for core::sync::atomic::AtomicU8 {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_has_atomic = "16")]
|
||||
impl SequenceCounter for core::sync::atomic::AtomicU16 {
|
||||
type Raw = u16;
|
||||
|
||||
@@ -147,6 +166,7 @@ impl SequenceCounter for core::sync::atomic::AtomicU16 {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_has_atomic = "32")]
|
||||
impl SequenceCounter for core::sync::atomic::AtomicU32 {
|
||||
type Raw = u32;
|
||||
|
||||
@@ -176,59 +196,63 @@ impl SequenceCounter for core::sync::atomic::AtomicU64 {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "portable-atomic")]
|
||||
impl SequenceCounter for portable_atomic::AtomicU8 {
|
||||
type Raw = u8;
|
||||
|
||||
const MAX_BIT_WIDTH: usize = 8;
|
||||
|
||||
fn get(&self) -> Self::Raw {
|
||||
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||
self.load(portable_atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn increment(&self) {
|
||||
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||
self.fetch_add(1, portable_atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "portable-atomic")]
|
||||
impl SequenceCounter for portable_atomic::AtomicU16 {
|
||||
type Raw = u16;
|
||||
|
||||
const MAX_BIT_WIDTH: usize = 16;
|
||||
|
||||
fn get(&self) -> Self::Raw {
|
||||
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||
self.load(portable_atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn increment(&self) {
|
||||
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||
self.fetch_add(1, portable_atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "portable-atomic")]
|
||||
impl SequenceCounter for portable_atomic::AtomicU32 {
|
||||
type Raw = u32;
|
||||
|
||||
const MAX_BIT_WIDTH: usize = 32;
|
||||
|
||||
fn get(&self) -> Self::Raw {
|
||||
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||
self.load(portable_atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn increment(&self) {
|
||||
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||
self.fetch_add(1, portable_atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "portable-atomic")]
|
||||
impl SequenceCounter for portable_atomic::AtomicU64 {
|
||||
type Raw = u64;
|
||||
|
||||
const MAX_BIT_WIDTH: usize = 64;
|
||||
|
||||
fn get(&self) -> Self::Raw {
|
||||
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||
self.load(portable_atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn increment(&self) {
|
||||
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||
self.fetch_add(1, portable_atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,6 +269,12 @@ impl<T: SequenceCounter + ?Sized> SequenceCounter for &T {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
target_has_atomic = "8",
|
||||
target_has_atomic = "16",
|
||||
target_has_atomic = "32",
|
||||
target_has_atomic = "64"
|
||||
))]
|
||||
macro_rules! sync_clonable_seq_counter_impl {
|
||||
($ty: ident) => {
|
||||
paste::paste! {
|
||||
@@ -257,6 +287,7 @@ macro_rules! sync_clonable_seq_counter_impl {
|
||||
}
|
||||
|
||||
impl [<SequenceCounterSyncCustomWrap $ty:upper>] {
|
||||
/// Generic constructor.
|
||||
pub fn new(max_val: $ty) -> Self {
|
||||
Self {
|
||||
seq_count: core::sync::atomic::[<Atomic $ty:upper>]::new(0),
|
||||
@@ -384,24 +415,28 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "portable-atomic")]
|
||||
fn test_portable_atomic_counter_u8() {
|
||||
let mut sync_u8_counter = portable_atomic::AtomicU8::new(0);
|
||||
common_counter_test(&mut sync_u8_counter);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "portable-atomic")]
|
||||
fn test_portable_atomic_counter_u16() {
|
||||
let mut sync_u16_counter = portable_atomic::AtomicU16::new(0);
|
||||
common_counter_test(&mut sync_u16_counter);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "portable-atomic")]
|
||||
fn test_portable_atomic_counter_u32() {
|
||||
let mut sync_u32_counter = portable_atomic::AtomicU32::new(0);
|
||||
common_counter_test(&mut sync_u32_counter);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "portable-atomic")]
|
||||
fn test_portable_atomic_counter_u64() {
|
||||
let mut sync_u64_counter = portable_atomic::AtomicU64::new(0);
|
||||
common_counter_test(&mut sync_u64_counter);
|
||||
@@ -421,6 +456,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "portable-atomic")]
|
||||
fn test_portable_atomic_u8_counter_overflow() {
|
||||
let sync_u8_counter = portable_atomic::AtomicU8::new(0);
|
||||
common_overflow_test_u8(&sync_u8_counter);
|
||||
|
||||
@@ -31,6 +31,7 @@ pub const FMT_STR_CODE_B_WITH_SIZE: (&str, usize) = ("%Y-%jT%T%.3f", 21);
|
||||
/// Three digits are used for the decimal fraction and a terminator is added at the end.
|
||||
pub const FMT_STR_CODE_B_TERMINATED_WITH_SIZE: (&str, usize) = ("%Y-%jT%T%.3fZ", 22);
|
||||
|
||||
/// Functions requiring both [chrono] and [alloc] support.
|
||||
#[cfg(all(feature = "alloc", feature = "chrono"))]
|
||||
pub mod alloc_mod_chrono {
|
||||
use super::*;
|
||||
|
||||
1685
src/time/cds.rs
1685
src/time/cds.rs
File diff suppressed because it is too large
Load Diff
@@ -32,6 +32,7 @@ pub const P_FIELD_BASE: u8 = (CcsdsTimeCode::CucCcsdsEpoch as u8) << 4;
|
||||
/// Maximum length if the preamble field is not extended.
|
||||
pub const MAX_CUC_LEN_SMALL_PREAMBLE: usize = 8;
|
||||
|
||||
/// Fractional resolution for the fractional part of the CUC time code.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -70,13 +71,14 @@ pub fn convert_fractional_part_to_ns(fractional_part: FractionalPart) -> u64 {
|
||||
10_u64.pow(9) * fractional_part.counter as u64 / div as u64
|
||||
}
|
||||
|
||||
/// Convert the fractional resolution to the divisor used to calculate the fractional part.
|
||||
#[inline(always)]
|
||||
pub const fn fractional_res_to_div(res: FractionalResolution) -> u32 {
|
||||
// We do not use the full possible range for a given resolution. This is because if we did
|
||||
// that, the largest value would be equal to the counter being incremented by one. Thus, the
|
||||
// smallest allowed fractions value is 0 while the largest allowed fractions value is the
|
||||
// closest fractions value to the next counter increment.
|
||||
2_u32.pow(8 * res as u32) - 1
|
||||
(1u32 << (8 * res as u32)) - 1
|
||||
}
|
||||
|
||||
/// Calculate the fractional part for a given resolution and subsecond nanoseconds.
|
||||
@@ -101,22 +103,34 @@ pub fn fractional_part_from_subsec_ns(res: FractionalResolution, ns: u64) -> Fra
|
||||
}
|
||||
}
|
||||
|
||||
/// CUC error.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug, thiserror::Error)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum CucError {
|
||||
/// Invalid CUC counter width.
|
||||
#[error("invalid cuc counter byte width {0}")]
|
||||
InvalidCounterWidth(u8),
|
||||
/// Invalid counter supplied.
|
||||
#[error("invalid cuc counter {counter} for width {width}")]
|
||||
InvalidCounter { width: u8, counter: u64 },
|
||||
InvalidCounter {
|
||||
/// Width.
|
||||
width: u8,
|
||||
/// Counter.
|
||||
counter: u64,
|
||||
},
|
||||
/// Invalid fractions.
|
||||
#[error("invalid cuc fractional part {value} for resolution {resolution:?}")]
|
||||
InvalidFractions {
|
||||
/// Resolution.
|
||||
resolution: FractionalResolution,
|
||||
/// Value.
|
||||
value: u64,
|
||||
},
|
||||
/// Error while correcting for leap seconds.
|
||||
#[error("error while correcting for leap seconds")]
|
||||
LeapSecondCorrectionError,
|
||||
/// Data is before the CCSDS epoch.
|
||||
#[error("date before ccsds epoch: {0}")]
|
||||
DateBeforeCcsdsEpoch(#[from] DateBeforeCcsdsEpochError),
|
||||
}
|
||||
@@ -127,14 +141,20 @@ pub enum CucError {
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct WidthCounterPair(pub u8, pub u32);
|
||||
|
||||
/// Fractional part of the CUC time code.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct FractionalPart {
|
||||
/// Resolution.
|
||||
pub resolution: FractionalResolution,
|
||||
/// Counter.
|
||||
pub counter: u32,
|
||||
}
|
||||
|
||||
impl FractionalPart {
|
||||
/// Generic constructor.
|
||||
///
|
||||
/// This function will panic if the counter is smaller than the calculated divisor.
|
||||
#[inline]
|
||||
pub const fn new(resolution: FractionalResolution, counter: u32) -> Self {
|
||||
let div = fractional_res_to_div(resolution);
|
||||
@@ -157,6 +177,7 @@ impl FractionalPart {
|
||||
Self::new_with_seconds_resolution()
|
||||
}
|
||||
|
||||
/// Check constructor which verifies that the counter is larger than the divisor.
|
||||
#[inline]
|
||||
pub fn new_checked(resolution: FractionalResolution, counter: u32) -> Option<Self> {
|
||||
let div = fractional_res_to_div(resolution);
|
||||
@@ -169,16 +190,19 @@ impl FractionalPart {
|
||||
})
|
||||
}
|
||||
|
||||
/// Fractional resolution.
|
||||
#[inline]
|
||||
pub fn resolution(&self) -> FractionalResolution {
|
||||
self.resolution
|
||||
}
|
||||
|
||||
/// Counter value.
|
||||
#[inline]
|
||||
pub fn counter(&self) -> u32 {
|
||||
self.counter
|
||||
}
|
||||
|
||||
/// Check whether the timestamp does not have a fractional part.
|
||||
#[inline]
|
||||
pub fn no_fractional_part(&self) -> bool {
|
||||
self.resolution == FractionalResolution::Seconds
|
||||
@@ -245,17 +269,21 @@ pub struct CucTime {
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct CucTimeWithLeapSecs {
|
||||
/// CUC time.
|
||||
pub time: CucTime,
|
||||
/// Leap seconds.
|
||||
pub leap_seconds: u32,
|
||||
}
|
||||
|
||||
impl CucTimeWithLeapSecs {
|
||||
/// Generic constructor.
|
||||
#[inline]
|
||||
pub fn new(time: CucTime, leap_seconds: u32) -> Self {
|
||||
Self { time, leap_seconds }
|
||||
}
|
||||
}
|
||||
|
||||
/// p-field length.
|
||||
#[inline]
|
||||
pub fn pfield_len(pfield: u8) -> usize {
|
||||
if ((pfield >> 7) & 0b1) == 1 {
|
||||
@@ -381,6 +409,7 @@ impl CucTime {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates a CUC timestamp from a Chrono DateTime object.
|
||||
#[cfg(feature = "chrono")]
|
||||
pub fn from_chrono_date_time(
|
||||
dt: &chrono::DateTime<chrono::Utc>,
|
||||
@@ -448,21 +477,25 @@ impl CucTime {
|
||||
})
|
||||
}
|
||||
|
||||
/// CCSDS time code.
|
||||
#[inline]
|
||||
pub fn ccsds_time_code(&self) -> CcsdsTimeCode {
|
||||
CcsdsTimeCode::CucCcsdsEpoch
|
||||
}
|
||||
|
||||
/// Width and counter pair.
|
||||
#[inline]
|
||||
pub fn width_counter_pair(&self) -> WidthCounterPair {
|
||||
self.counter
|
||||
}
|
||||
|
||||
/// Counter width.
|
||||
#[inline]
|
||||
pub fn counter_width(&self) -> u8 {
|
||||
self.counter.0
|
||||
}
|
||||
|
||||
/// Counter value.
|
||||
#[inline]
|
||||
pub fn counter(&self) -> u32 {
|
||||
self.counter.1
|
||||
@@ -474,11 +507,13 @@ impl CucTime {
|
||||
self.fractions
|
||||
}
|
||||
|
||||
/// Convert to the leap seconds helper.
|
||||
#[inline]
|
||||
pub fn to_leap_sec_helper(&self, leap_seconds: u32) -> CucTimeWithLeapSecs {
|
||||
CucTimeWithLeapSecs::new(*self, leap_seconds)
|
||||
}
|
||||
|
||||
/// Set the fractional part.
|
||||
#[inline]
|
||||
pub fn set_fractions(&mut self, fractions: FractionalPart) -> Result<(), CucError> {
|
||||
Self::verify_fractions_value(fractions)?;
|
||||
@@ -525,16 +560,19 @@ impl CucTime {
|
||||
self.pfield |= self.fractions.resolution() as u8;
|
||||
}
|
||||
|
||||
/// Length of the counter from the p-field.
|
||||
#[inline]
|
||||
pub fn len_cntr_from_pfield(pfield: u8) -> u8 {
|
||||
((pfield >> 2) & 0b11) + 1
|
||||
}
|
||||
|
||||
/// Length of the fractional part from the p-field.
|
||||
#[inline]
|
||||
pub fn len_fractions_from_pfield(pfield: u8) -> u8 {
|
||||
pfield & 0b11
|
||||
}
|
||||
|
||||
/// UNIX seconds.
|
||||
#[inline]
|
||||
pub fn unix_secs(&self, leap_seconds: u32) -> i64 {
|
||||
ccsds_epoch_to_unix_epoch(self.counter.1 as i64)
|
||||
@@ -542,6 +580,7 @@ impl CucTime {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Subsecond milliseconds part of the CUC time.
|
||||
#[inline]
|
||||
pub fn subsec_millis(&self) -> u16 {
|
||||
(self.subsec_nanos() / 1_000_000) as u16
|
||||
@@ -564,6 +603,7 @@ impl CucTime {
|
||||
)
|
||||
}
|
||||
|
||||
/// Packed length from the raw p-field.
|
||||
#[inline]
|
||||
pub fn len_packed_from_pfield(pfield: u8) -> usize {
|
||||
let mut base_len: usize = 1;
|
||||
|
||||
@@ -22,19 +22,29 @@ pub mod ascii;
|
||||
pub mod cds;
|
||||
pub mod cuc;
|
||||
|
||||
/// Conversion constant for converting CCSDS days to UNIX days.
|
||||
pub const DAYS_CCSDS_TO_UNIX: i32 = -4383;
|
||||
/// Seconds per day.
|
||||
pub const SECONDS_PER_DAY: u32 = 86400;
|
||||
/// Milliseconds per day.
|
||||
pub const MS_PER_DAY: u32 = SECONDS_PER_DAY * 1000;
|
||||
/// Nanoseconds per second.
|
||||
pub const NANOS_PER_SECOND: u32 = 1_000_000_000;
|
||||
|
||||
/// CCSDS time code identifiers.
|
||||
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum CcsdsTimeCode {
|
||||
/// CUC with a CCSDS epoch (1958-01-01T00:00:00+00:00).
|
||||
CucCcsdsEpoch = 0b001,
|
||||
/// CUC with a custom agency epoch.
|
||||
CucAgencyEpoch = 0b010,
|
||||
/// CDS time code.
|
||||
Cds = 0b100,
|
||||
/// CCS time code.
|
||||
Ccs = 0b101,
|
||||
/// Agency defined time code.
|
||||
AgencyDefined = 0b110,
|
||||
}
|
||||
|
||||
@@ -60,44 +70,61 @@ pub fn ccsds_time_code_from_p_field(pfield: u8) -> Result<CcsdsTimeCode, u8> {
|
||||
CcsdsTimeCode::try_from(raw_bits).map_err(|_| raw_bits)
|
||||
}
|
||||
|
||||
/// Date is before the CCSDS epoch.
|
||||
#[derive(Debug, PartialEq, Eq, Copy, Clone, thiserror::Error)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[error("date before ccsds epoch: {0:?}")]
|
||||
pub struct DateBeforeCcsdsEpochError(UnixTime);
|
||||
|
||||
/// Generic timestamp error.
|
||||
#[derive(Debug, PartialEq, Eq, Copy, Clone, thiserror::Error)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[non_exhaustive]
|
||||
pub enum TimestampError {
|
||||
/// Invalid time code.
|
||||
#[error("invalid time code, expected {expected:?}, found {found}")]
|
||||
InvalidTimeCode { expected: CcsdsTimeCode, found: u8 },
|
||||
InvalidTimeCode {
|
||||
/// Expected time code.
|
||||
expected: CcsdsTimeCode,
|
||||
/// Found raw time code.
|
||||
found: u8,
|
||||
},
|
||||
/// Byte conversion error.
|
||||
#[error("time stamp: byte conversion error: {0}")]
|
||||
ByteConversion(#[from] ByteConversionError),
|
||||
/// CDS timestamp error.
|
||||
#[error("CDS error: {0}")]
|
||||
Cds(#[from] cds::CdsError),
|
||||
/// CUC timestamp error.
|
||||
#[error("CUC error: {0}")]
|
||||
Cuc(#[from] cuc::CucError),
|
||||
/// Custom epoch is not supported.
|
||||
#[error("custom epoch not supported")]
|
||||
CustomEpochNotSupported,
|
||||
}
|
||||
|
||||
/// [std] module.
|
||||
#[cfg(feature = "std")]
|
||||
pub mod std_mod {
|
||||
use crate::time::TimestampError;
|
||||
use std::time::SystemTimeError;
|
||||
use thiserror::Error;
|
||||
|
||||
/// [std] timestamp error.
|
||||
#[derive(Debug, Clone, Error)]
|
||||
pub enum StdTimestampError {
|
||||
/// System time error.
|
||||
#[error("system time error: {0:?}")]
|
||||
SystemTime(#[from] SystemTimeError),
|
||||
/// Generic timestamp error.
|
||||
#[error("timestamp error: {0}")]
|
||||
Timestamp(#[from] TimestampError),
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds since epoch for the current system time.
|
||||
#[cfg(feature = "std")]
|
||||
pub fn seconds_since_epoch() -> f64 {
|
||||
SystemTime::now()
|
||||
@@ -131,16 +158,19 @@ pub const fn unix_epoch_to_ccsds_epoch(unix_epoch: i64) -> i64 {
|
||||
unix_epoch - (DAYS_CCSDS_TO_UNIX as i64 * SECONDS_PER_DAY as i64)
|
||||
}
|
||||
|
||||
/// Convert CCSDS epoch to UNIX epoch.
|
||||
#[inline]
|
||||
pub const fn ccsds_epoch_to_unix_epoch(ccsds_epoch: i64) -> i64 {
|
||||
ccsds_epoch + (DAYS_CCSDS_TO_UNIX as i64 * SECONDS_PER_DAY as i64)
|
||||
}
|
||||
|
||||
/// Milliseconds of day for the current system time.
|
||||
#[cfg(feature = "std")]
|
||||
pub fn ms_of_day_using_sysclock() -> u32 {
|
||||
ms_of_day(seconds_since_epoch())
|
||||
}
|
||||
|
||||
/// Milliseconds for the given seconds since epoch.
|
||||
pub fn ms_of_day(seconds_since_epoch: f64) -> u32 {
|
||||
let fraction_ms = seconds_since_epoch - seconds_since_epoch.floor();
|
||||
let ms_of_day: u32 = (((seconds_since_epoch.floor() as u32 % SECONDS_PER_DAY) * 1000) as f64
|
||||
@@ -149,13 +179,16 @@ pub fn ms_of_day(seconds_since_epoch: f64) -> u32 {
|
||||
ms_of_day
|
||||
}
|
||||
|
||||
/// Generic writable timestamp trait.
|
||||
pub trait TimeWriter {
|
||||
/// Written length.
|
||||
fn len_written(&self) -> usize;
|
||||
|
||||
/// Generic function to convert write a timestamp into a raw buffer.
|
||||
/// Returns the number of written bytes on success.
|
||||
fn write_to_bytes(&self, bytes: &mut [u8]) -> Result<usize, TimestampError>;
|
||||
|
||||
/// Convert to a owned [alloc::vec::Vec].
|
||||
#[cfg(feature = "alloc")]
|
||||
fn to_vec(&self) -> Result<alloc::vec::Vec<u8>, TimestampError> {
|
||||
let mut vec = alloc::vec![0; self.len_written()];
|
||||
@@ -164,7 +197,9 @@ pub trait TimeWriter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Genmeric readable timestamp trait.
|
||||
pub trait TimeReader: Sized {
|
||||
/// Create a timestamp from a raw byte buffer.
|
||||
fn from_bytes(buf: &[u8]) -> Result<Self, TimestampError>;
|
||||
}
|
||||
|
||||
@@ -174,6 +209,7 @@ pub trait TimeReader: Sized {
|
||||
/// practical because they are a very common and simple exchange format for time information.
|
||||
/// Therefore, it was decided to keep them in this trait as well.
|
||||
pub trait CcsdsTimeProvider {
|
||||
/// Length when written to bytes.
|
||||
fn len_as_bytes(&self) -> usize;
|
||||
|
||||
/// Returns the pfield of the time provider. The pfield can have one or two bytes depending
|
||||
@@ -181,24 +217,37 @@ pub trait CcsdsTimeProvider {
|
||||
/// entry denotes the length of the pfield and the second entry is the value of the pfield
|
||||
/// in big endian format.
|
||||
fn p_field(&self) -> (usize, [u8; 2]);
|
||||
|
||||
/// CCSDS time code field.
|
||||
fn ccdsd_time_code(&self) -> CcsdsTimeCode;
|
||||
|
||||
fn unix_secs(&self) -> i64;
|
||||
fn subsec_nanos(&self) -> u32;
|
||||
/// UNIX time as seconds.
|
||||
fn unix_secs(&self) -> i64 {
|
||||
self.unix_time().secs
|
||||
}
|
||||
|
||||
/// Subsecond nanoseconds.
|
||||
fn subsec_nanos(&self) -> u32 {
|
||||
self.unix_time().subsec_nanos
|
||||
}
|
||||
|
||||
/// Subsecond milliseconds.
|
||||
fn subsec_millis(&self) -> u16 {
|
||||
(self.subsec_nanos() / 1_000_000) as u16
|
||||
}
|
||||
|
||||
/// UNIX time.
|
||||
fn unix_time(&self) -> UnixTime {
|
||||
UnixTime::new(self.unix_secs(), self.subsec_nanos())
|
||||
}
|
||||
|
||||
/// [chrono] date time.
|
||||
#[cfg(feature = "chrono")]
|
||||
fn chrono_date_time(&self) -> chrono::LocalResult<chrono::DateTime<chrono::Utc>> {
|
||||
chrono::Utc.timestamp_opt(self.unix_secs(), self.subsec_nanos())
|
||||
}
|
||||
|
||||
/// [time] library date] library date time.
|
||||
#[cfg(feature = "timelib")]
|
||||
fn timelib_date_time(&self) -> Result<time::OffsetDateTime, time::error::ComponentRange> {
|
||||
Ok(time::OffsetDateTime::from_unix_timestamp(self.unix_secs())?
|
||||
@@ -280,6 +329,7 @@ impl UnixTime {
|
||||
}
|
||||
}
|
||||
|
||||
/// New UNIX time with only seconds, subseconds set to zero.
|
||||
pub fn new_only_secs(unix_seconds: i64) -> Self {
|
||||
Self {
|
||||
secs: unix_seconds,
|
||||
@@ -287,15 +337,18 @@ impl UnixTime {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sub-second milliseconds.
|
||||
#[inline]
|
||||
pub fn subsec_millis(&self) -> u16 {
|
||||
(self.subsec_nanos / 1_000_000) as u16
|
||||
}
|
||||
|
||||
/// Sub-second nanoseconds.
|
||||
pub fn subsec_nanos(&self) -> u32 {
|
||||
self.subsec_nanos
|
||||
}
|
||||
|
||||
/// Create a UNIX timestamp from the current system time.
|
||||
#[cfg(feature = "std")]
|
||||
pub fn now() -> Result<Self, SystemTimeError> {
|
||||
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
|
||||
@@ -303,27 +356,31 @@ impl UnixTime {
|
||||
Ok(Self::new(epoch as i64, now.subsec_nanos()))
|
||||
}
|
||||
|
||||
/// UNIX timestamp as a floating point number in seconds.
|
||||
#[inline]
|
||||
pub fn unix_secs_f64(&self) -> f64 {
|
||||
self.secs as f64 + (self.subsec_nanos as f64 / 1_000_000_000.0)
|
||||
}
|
||||
|
||||
/// UNIX timestamp as seconds, discards the sub-second part.
|
||||
pub fn as_secs(&self) -> i64 {
|
||||
self.secs
|
||||
}
|
||||
|
||||
/// UNIX timestamp as [chrono] date time.
|
||||
#[cfg(feature = "chrono")]
|
||||
pub fn chrono_date_time(&self) -> chrono::LocalResult<chrono::DateTime<chrono::Utc>> {
|
||||
Utc.timestamp_opt(self.secs, self.subsec_nanos)
|
||||
}
|
||||
|
||||
/// UNIX timestamp as [time] library date time.
|
||||
#[cfg(feature = "timelib")]
|
||||
pub fn timelib_date_time(&self) -> Result<time::OffsetDateTime, time::error::ComponentRange> {
|
||||
Ok(time::OffsetDateTime::from_unix_timestamp(self.as_secs())?
|
||||
+ time::Duration::nanoseconds(self.subsec_nanos().into()))
|
||||
}
|
||||
|
||||
// Calculate the difference in milliseconds between two UnixTimestamps
|
||||
/// Calculate the difference in milliseconds between two UnixTimestamps
|
||||
pub fn diff_in_millis(&self, other: &UnixTime) -> Option<i64> {
|
||||
let seconds_difference = self.secs.checked_sub(other.secs)?;
|
||||
// Convert seconds difference to milliseconds
|
||||
@@ -393,7 +450,9 @@ impl Ord for UnixTime {
|
||||
/// so the sign information is supplied separately.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StampDiff {
|
||||
/// Positive duration flag.
|
||||
pub positive_duration: bool,
|
||||
/// Absolute duration.
|
||||
pub duration_absolute: Duration,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/// # Support of the CCSDS Unified Space Data Link Protocol (USLP)
|
||||
//! # Support of the CCSDS Unified Space Data Link Protocol (USLP)
|
||||
#![warn(missing_docs)]
|
||||
use crate::{crc::CRC_CCITT_FALSE, ByteConversionError};
|
||||
|
||||
/// Only this version is supported by the library
|
||||
@@ -17,6 +18,7 @@ pub enum SourceOrDestField {
|
||||
Dest = 1,
|
||||
}
|
||||
|
||||
/// Bypass sequence control flag.
|
||||
#[derive(Debug, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -30,6 +32,7 @@ pub enum BypassSequenceControlFlag {
|
||||
ExpeditedQoS = 1,
|
||||
}
|
||||
|
||||
/// Protcol Control Command Flag.
|
||||
#[derive(
|
||||
Debug, Copy, Clone, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive,
|
||||
)]
|
||||
@@ -37,55 +40,77 @@ pub enum BypassSequenceControlFlag {
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum ProtocolControlCommandFlag {
|
||||
/// Transfer frame data field contains user data.
|
||||
TfdfContainsUserData = 0,
|
||||
/// Transfer frame data field contains protocol information.
|
||||
TfdfContainsProtocolInfo = 1,
|
||||
}
|
||||
|
||||
/// USLP error enumeration.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum UslpError {
|
||||
/// Byte conversion error.
|
||||
#[error("byte conversion error: {0}")]
|
||||
ByteConversion(#[from] ByteConversionError),
|
||||
/// Header is truncated, which is not supported.
|
||||
#[error("header is truncated, which is not supported")]
|
||||
HeaderIsTruncated,
|
||||
/// Invalid protocol ID.
|
||||
#[error("invalid protocol id: {0}")]
|
||||
InvalidProtocolId(u8),
|
||||
/// Invalid construction rule.
|
||||
#[error("invalid construction rule: {0}")]
|
||||
InvalidConstructionRule(u8),
|
||||
/// Invalid version number.
|
||||
#[error("invalid version number: {0}")]
|
||||
InvalidVersionNumber(u8),
|
||||
/// Invalid virtual channel ID.
|
||||
#[error("invalid virtual channel ID: {0}")]
|
||||
InvalidVcId(u8),
|
||||
/// Invalid MAP ID.
|
||||
#[error("invalid MAP ID: {0}")]
|
||||
InvalidMapId(u8),
|
||||
/// Checksum failure.
|
||||
#[error("checksum failure")]
|
||||
ChecksumFailure(u16),
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
/// Invalid value for length.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct InvalidValueForLen {
|
||||
#[error("invalid value for length of the field")]
|
||||
pub struct InvalidValueForLenError {
|
||||
value: u64,
|
||||
len: u8,
|
||||
}
|
||||
|
||||
/// Primary header of a USLP transfer frame.
|
||||
#[derive(Debug, Copy, Clone, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PrimaryHeader {
|
||||
/// Spacecraft ID.
|
||||
pub spacecraft_id: u16,
|
||||
/// Source or destination identifier.
|
||||
pub source_or_dest_field: SourceOrDestField,
|
||||
/// Virtual channel ID.
|
||||
pub vc_id: u8,
|
||||
/// MAP ID.
|
||||
pub map_id: u8,
|
||||
frame_len_field: u16,
|
||||
/// Bypass sequence control flag.
|
||||
pub sequence_control_flag: BypassSequenceControlFlag,
|
||||
/// Procol control command flag.
|
||||
pub protocol_control_command_flag: ProtocolControlCommandFlag,
|
||||
/// Operational control field flag.
|
||||
pub ocf_flag: bool,
|
||||
vc_frame_count_len: u8,
|
||||
vc_frame_count: u64,
|
||||
}
|
||||
|
||||
impl PrimaryHeader {
|
||||
/// Generic constructor.
|
||||
pub fn new(
|
||||
spacecraft_id: u16,
|
||||
source_or_dest_field: SourceOrDestField,
|
||||
@@ -113,13 +138,14 @@ impl PrimaryHeader {
|
||||
})
|
||||
}
|
||||
|
||||
/// Set the virtual channel frame count.
|
||||
pub fn set_vc_frame_count(
|
||||
&mut self,
|
||||
count_len: u8,
|
||||
count: u64,
|
||||
) -> Result<(), InvalidValueForLen> {
|
||||
) -> Result<(), InvalidValueForLenError> {
|
||||
if count > 2_u64.pow(count_len as u32 * 8) - 1 {
|
||||
return Err(InvalidValueForLen {
|
||||
return Err(InvalidValueForLenError {
|
||||
value: count,
|
||||
len: count_len,
|
||||
});
|
||||
@@ -129,16 +155,19 @@ impl PrimaryHeader {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Virtual channel frame count.
|
||||
#[inline]
|
||||
pub fn vc_frame_count(&self) -> u64 {
|
||||
self.vc_frame_count
|
||||
}
|
||||
|
||||
/// Length of the virtual channel frame count field.
|
||||
#[inline]
|
||||
pub fn vc_frame_count_len(&self) -> u8 {
|
||||
self.vc_frame_count_len
|
||||
}
|
||||
|
||||
/// Parse [Self] from raw bytes.
|
||||
pub fn from_bytes(buf: &[u8]) -> Result<Self, UslpError> {
|
||||
if buf.len() < 4 {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
@@ -207,6 +236,7 @@ impl PrimaryHeader {
|
||||
})
|
||||
}
|
||||
|
||||
/// Write primary header to bytes.
|
||||
pub fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
if buf.len() < self.len_header() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
@@ -233,6 +263,7 @@ impl PrimaryHeader {
|
||||
Ok(self.len_header())
|
||||
}
|
||||
|
||||
/// Set frame length field.
|
||||
#[inline(always)]
|
||||
pub fn set_frame_len(&mut self, frame_len: usize) {
|
||||
// 4.1.2.7.2
|
||||
@@ -241,11 +272,13 @@ impl PrimaryHeader {
|
||||
self.frame_len_field = frame_len.saturating_sub(1) as u16;
|
||||
}
|
||||
|
||||
/// Length of primary header when written to bytes.
|
||||
#[inline(always)]
|
||||
pub fn len_header(&self) -> usize {
|
||||
7 + self.vc_frame_count_len as usize
|
||||
}
|
||||
|
||||
/// Length of the entire frame.
|
||||
#[inline(always)]
|
||||
pub fn len_frame(&self) -> usize {
|
||||
// 4.1.2.7.2
|
||||
@@ -271,6 +304,7 @@ impl PartialEq for PrimaryHeader {
|
||||
}
|
||||
}
|
||||
|
||||
/// USLP protocol ID enumeration.
|
||||
#[derive(Debug, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -278,6 +312,7 @@ impl PartialEq for PrimaryHeader {
|
||||
#[repr(u8)]
|
||||
#[non_exhaustive]
|
||||
pub enum UslpProtocolId {
|
||||
/// Space packets or encapsulation packets.
|
||||
SpacePacketsOrEncapsulation = 0b00000,
|
||||
/// COP-1 control commands within the TFDZ.
|
||||
Cop1ControlCommands = 0b00001,
|
||||
@@ -285,6 +320,7 @@ pub enum UslpProtocolId {
|
||||
CopPControlCommands = 0b00010,
|
||||
/// SDLS control commands within the TFDZ.
|
||||
Sdls = 0b00011,
|
||||
/// User defined octet stream.
|
||||
UserDefinedOctetStream = 0b00100,
|
||||
/// Proximity-1 Supervisory Protocol Data Units (SPDUs) within the TFDZ.
|
||||
Spdu = 0b00111,
|
||||
@@ -292,6 +328,7 @@ pub enum UslpProtocolId {
|
||||
Idle = 0b11111,
|
||||
}
|
||||
|
||||
/// USLP construction rule enumeration.
|
||||
#[derive(Debug, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -302,16 +339,25 @@ pub enum ConstructionRule {
|
||||
/// span transfer frame boundaries. The First Header Pointer (FHP) is required for packet
|
||||
/// extraction.
|
||||
PacketSpanningMultipleFrames = 0b000,
|
||||
/// Start of a MAPA SDU or VCA SDU.
|
||||
StartOfMapaSduOrVcaSdu = 0b001,
|
||||
/// Continuing portion of a MAPA SDU.
|
||||
ContinuingPortionOfMapaSdu = 0b010,
|
||||
/// Octet stream.
|
||||
OctetStream = 0b011,
|
||||
/// Starting segment.
|
||||
StartingSegment = 0b100,
|
||||
/// Continuing segment.
|
||||
ContinuingSegment = 0b101,
|
||||
/// Last segment.
|
||||
LastSegment = 0b110,
|
||||
/// No segmentation.
|
||||
NoSegmentation = 0b111,
|
||||
}
|
||||
|
||||
impl ConstructionRule {
|
||||
/// Is the construction rule applicable to fixed-length TFDZs?
|
||||
#[inline]
|
||||
pub const fn applicable_to_fixed_len_tfdz(&self) -> bool {
|
||||
match self {
|
||||
ConstructionRule::PacketSpanningMultipleFrames => true,
|
||||
@@ -326,6 +372,7 @@ impl ConstructionRule {
|
||||
}
|
||||
}
|
||||
|
||||
/// Transfer frame data field header.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub struct TransferFrameDataFieldHeader {
|
||||
/// Construction rule for the TFDZ.
|
||||
@@ -337,6 +384,7 @@ pub struct TransferFrameDataFieldHeader {
|
||||
}
|
||||
|
||||
impl TransferFrameDataFieldHeader {
|
||||
/// Length of the header when written to bytes.
|
||||
#[inline]
|
||||
pub const fn len_header(&self) -> usize {
|
||||
if self.construction_rule.applicable_to_fixed_len_tfdz() {
|
||||
@@ -346,21 +394,25 @@ impl TransferFrameDataFieldHeader {
|
||||
}
|
||||
}
|
||||
|
||||
/// Construction rule.
|
||||
#[inline]
|
||||
pub const fn construction_rule(&self) -> ConstructionRule {
|
||||
self.construction_rule
|
||||
}
|
||||
|
||||
/// USLP protocol ID.
|
||||
#[inline]
|
||||
pub const fn uslp_protocol_id(&self) -> UslpProtocolId {
|
||||
self.uslp_protocol_id
|
||||
}
|
||||
|
||||
/// FHP or LVO field when present.
|
||||
#[inline]
|
||||
pub const fn fhp_or_lvo(&self) -> Option<u16> {
|
||||
self.fhp_or_lvo
|
||||
}
|
||||
|
||||
/// Parse [Self] from raw bytes.
|
||||
pub fn from_bytes(buf: &[u8]) -> Result<Self, UslpError> {
|
||||
if buf.is_empty() {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
@@ -451,29 +503,34 @@ impl<'buf> TransferFrameReader<'buf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Length of the entire frame.
|
||||
#[inline]
|
||||
pub fn len_frame(&self) -> usize {
|
||||
self.primary_header.len_frame()
|
||||
}
|
||||
|
||||
/// Primary header.
|
||||
#[inline]
|
||||
pub fn primary_header(&self) -> &PrimaryHeader {
|
||||
&self.primary_header
|
||||
}
|
||||
|
||||
/// Transfer frame data field header.
|
||||
#[inline]
|
||||
pub fn data_field_header(&self) -> &TransferFrameDataFieldHeader {
|
||||
&self.data_field_header
|
||||
}
|
||||
|
||||
/// Data contained in the transfer frame data field.
|
||||
#[inline]
|
||||
pub fn data(&self) -> &'buf [u8] {
|
||||
self.data
|
||||
}
|
||||
|
||||
/// Operational control field when present.
|
||||
#[inline]
|
||||
pub fn operational_control_field(&self) -> &Option<u32> {
|
||||
&self.operational_control_field
|
||||
pub fn operational_control_field(&self) -> Option<u32> {
|
||||
self.operational_control_field
|
||||
}
|
||||
}
|
||||
|
||||
@@ -705,11 +762,11 @@ mod tests {
|
||||
.unwrap();
|
||||
matches!(
|
||||
primary_header.set_vc_frame_count(0, 1).unwrap_err(),
|
||||
InvalidValueForLen { value: 1, len: 0 }
|
||||
InvalidValueForLenError { value: 1, len: 0 }
|
||||
);
|
||||
matches!(
|
||||
primary_header.set_vc_frame_count(1, 256).unwrap_err(),
|
||||
InvalidValueForLen { value: 256, len: 1 }
|
||||
InvalidValueForLenError { value: 256, len: 1 }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
58
src/util.rs
58
src/util.rs
@@ -1,12 +1,16 @@
|
||||
//! # Utility module.
|
||||
use crate::ByteConversionError;
|
||||
use core::fmt::Debug;
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Helper traits for types which can be converted to a byte array.
|
||||
pub trait ToBeBytes {
|
||||
/// Concrete byte array type.
|
||||
type ByteArray: AsRef<[u8]>;
|
||||
/// Length when written to big endian bytes.
|
||||
fn written_len(&self) -> usize;
|
||||
/// Convert to big endian byte array.
|
||||
fn to_be_bytes(&self) -> Self::ByteArray;
|
||||
}
|
||||
|
||||
@@ -80,14 +84,17 @@ impl ToBeBytes for u64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper trait for unsigned enumerations.
|
||||
pub trait UnsignedEnum {
|
||||
/// Size of the unsigned enumeration in bytes.
|
||||
fn size(&self) -> usize;
|
||||
/// Write the unsigned enumeration to a raw buffer. Returns the written size on success.
|
||||
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;
|
||||
|
||||
fn value(&self) -> u64;
|
||||
/// Type-erased raw value.
|
||||
fn value_raw(&self) -> u64;
|
||||
|
||||
/// Convert to a [alloc::vec::Vec].
|
||||
#[cfg(feature = "alloc")]
|
||||
fn to_vec(&self) -> alloc::vec::Vec<u8> {
|
||||
let mut buf = alloc::vec![0; self.size()];
|
||||
@@ -96,22 +103,32 @@ pub trait UnsignedEnum {
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension trait for unsigned enumerations.
|
||||
pub trait UnsignedEnumExt: UnsignedEnum + Debug + Copy + Clone + PartialEq + Eq {}
|
||||
|
||||
/// Unsigned byte field errors.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum UnsignedByteFieldError {
|
||||
/// Value is too large for specified width of byte field.
|
||||
#[error("value {value} too large for width {width}")]
|
||||
ValueTooLargeForWidth { width: usize, value: u64 },
|
||||
ValueTooLargeForWidth {
|
||||
/// Width in bytes.
|
||||
width: usize,
|
||||
/// Value.
|
||||
value: u64,
|
||||
},
|
||||
/// Only 1, 2, 4 and 8 are allow width values. Optionally contains the expected width if
|
||||
/// applicable, for example for conversions.
|
||||
#[error("invalid width {found}, expected {expected:?}")]
|
||||
InvalidWidth {
|
||||
/// Found width.
|
||||
found: usize,
|
||||
/// Expected width.
|
||||
expected: Option<usize>,
|
||||
},
|
||||
/// Error during byte conversion.
|
||||
#[error("byte conversion error: {0}")]
|
||||
ByteConversionError(#[from] ByteConversionError),
|
||||
}
|
||||
@@ -126,16 +143,19 @@ pub struct UnsignedByteField {
|
||||
}
|
||||
|
||||
impl UnsignedByteField {
|
||||
/// Generic constructor.
|
||||
#[inline]
|
||||
pub const fn new(width: usize, value: u64) -> Self {
|
||||
Self { width, value }
|
||||
}
|
||||
|
||||
/// Type-erased raw value.
|
||||
#[inline]
|
||||
pub const fn value_const(&self) -> u64 {
|
||||
pub const fn value(&self) -> u64 {
|
||||
self.value
|
||||
}
|
||||
|
||||
/// Construct from raw bytes, assuming big-endian byte order.
|
||||
#[inline]
|
||||
pub fn new_from_be_bytes(width: usize, buf: &[u8]) -> Result<Self, UnsignedByteFieldError> {
|
||||
if width > buf.len() {
|
||||
@@ -175,8 +195,8 @@ impl UnsignedEnum for UnsignedByteField {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn value(&self) -> u64 {
|
||||
self.value_const()
|
||||
fn value_raw(&self) -> u64 {
|
||||
self.value()
|
||||
}
|
||||
|
||||
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
@@ -212,6 +232,7 @@ impl UnsignedEnum for UnsignedByteField {
|
||||
}
|
||||
}
|
||||
|
||||
/// Generic type erased unsigned byte field.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
@@ -220,11 +241,13 @@ pub struct GenericUnsignedByteField<TYPE: Copy + Into<u64>> {
|
||||
}
|
||||
|
||||
impl<TYPE: Copy + Into<u64>> GenericUnsignedByteField<TYPE> {
|
||||
/// Generic constructor.
|
||||
pub const fn new(val: TYPE) -> Self {
|
||||
Self { value: val }
|
||||
}
|
||||
|
||||
pub const fn value_typed(&self) -> TYPE {
|
||||
/// Raw value.
|
||||
pub const fn value(&self) -> TYPE {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
@@ -247,20 +270,29 @@ impl<TYPE: Copy + ToBeBytes + Into<u64>> UnsignedEnum for GenericUnsignedByteFie
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn value(&self) -> u64 {
|
||||
self.value_typed().into()
|
||||
fn value_raw(&self) -> u64 {
|
||||
self.value().into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Alias for [GenericUnsignedByteField] with [()] generic.
|
||||
pub type UnsignedByteFieldEmpty = GenericUnsignedByteField<()>;
|
||||
/// Alias for [GenericUnsignedByteField] with [u8] generic.
|
||||
pub type UnsignedByteFieldU8 = GenericUnsignedByteField<u8>;
|
||||
/// Alias for [GenericUnsignedByteField] with [u16] generic.
|
||||
pub type UnsignedByteFieldU16 = GenericUnsignedByteField<u16>;
|
||||
/// Alias for [GenericUnsignedByteField] with [u32] generic.
|
||||
pub type UnsignedByteFieldU32 = GenericUnsignedByteField<u32>;
|
||||
/// Alias for [GenericUnsignedByteField] with [u64] generic.
|
||||
pub type UnsignedByteFieldU64 = GenericUnsignedByteField<u64>;
|
||||
|
||||
/// Alias for [UnsignedByteFieldU8]
|
||||
pub type UbfU8 = UnsignedByteFieldU8;
|
||||
/// Alias for [UnsignedByteFieldU16]
|
||||
pub type UbfU16 = UnsignedByteFieldU16;
|
||||
/// Alias for [UnsignedByteFieldU32]
|
||||
pub type UbfU32 = UnsignedByteFieldU32;
|
||||
/// Alias for [UnsignedByteFieldU64]
|
||||
pub type UbfU64 = UnsignedByteFieldU64;
|
||||
|
||||
impl From<UnsignedByteFieldU8> for UnsignedByteField {
|
||||
@@ -351,7 +383,7 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU64 {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
mod tests {
|
||||
use crate::util::{
|
||||
UnsignedByteField, UnsignedByteFieldError, UnsignedByteFieldU16, UnsignedByteFieldU32,
|
||||
UnsignedByteFieldU64, UnsignedByteFieldU8, UnsignedEnum,
|
||||
@@ -372,7 +404,7 @@ pub mod tests {
|
||||
for val in buf.iter().skip(1) {
|
||||
assert_eq!(*val, 0);
|
||||
}
|
||||
assert_eq!(u8.value_typed(), 5);
|
||||
assert_eq!(u8.value_raw(), 5);
|
||||
assert_eq!(u8.value(), 5);
|
||||
}
|
||||
|
||||
@@ -390,7 +422,7 @@ pub mod tests {
|
||||
for val in buf.iter().skip(2) {
|
||||
assert_eq!(*val, 0);
|
||||
}
|
||||
assert_eq!(u16.value_typed(), 3823);
|
||||
assert_eq!(u16.value_raw(), 3823);
|
||||
assert_eq!(u16.value(), 3823);
|
||||
}
|
||||
|
||||
@@ -408,7 +440,7 @@ pub mod tests {
|
||||
(4..8).for_each(|i| {
|
||||
assert_eq!(buf[i], 0);
|
||||
});
|
||||
assert_eq!(u32.value_typed(), 80932);
|
||||
assert_eq!(u32.value_raw(), 80932);
|
||||
assert_eq!(u32.value(), 80932);
|
||||
}
|
||||
|
||||
@@ -423,7 +455,7 @@ pub mod tests {
|
||||
assert_eq!(len, 8);
|
||||
let raw_val = u64::from_be_bytes(buf[0..8].try_into().unwrap());
|
||||
assert_eq!(raw_val, 5999999);
|
||||
assert_eq!(u64.value_typed(), 5999999);
|
||||
assert_eq!(u64.value_raw(), 5999999);
|
||||
assert_eq!(u64.value(), 5999999);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user