Compare commits
94 Commits
v0.6.0
...
v0.7.0-bet
Author | SHA1 | Date | |
---|---|---|---|
e935b3825a | |||
a49737fc34
|
|||
3081539bb2 | |||
1b01c8bb0b
|
|||
2ee3eee32e
|
|||
406d731bbe
|
|||
49b50ec682
|
|||
00fdfde015 | |||
491b03c701
|
|||
e090beedde
|
|||
6f2ed3003f | |||
0b5a384743
|
|||
925b2aa8d8
|
|||
d98d4b55c8
|
|||
94c378fa3b | |||
1fc15230fa | |||
e78f196a42
|
|||
2a11359a81 | |||
c226c5ea0f
|
|||
ab65845573 | |||
3206af690c
|
|||
805065a7b9
|
|||
62533bb91c | |||
c085f9ab32 | |||
f208a9b0f0
|
|||
c96a86a994
|
|||
9dfc593d2a
|
|||
990b8de519
|
|||
965541e422
|
|||
9a52066314
|
|||
6ab05e2d83
|
|||
2d81a79321
|
|||
fc7bee342c | |||
1789cff2b8
|
|||
5ae5abe09a
|
|||
407d1e1154
|
|||
3ba575aac1
|
|||
81db36d159
|
|||
081f6e840f
|
|||
3cb19298c8
|
|||
4e2c0f1aa7
|
|||
83db710950
|
|||
0f49672829 | |||
ffd1bf3769
|
|||
ccf7592284
|
|||
2b7fcbdd8e
|
|||
e389f77063
|
|||
fcf4449c14 | |||
05916130a8
|
|||
4b7f2b4817 | |||
91e7d8549c
|
|||
3430275638 | |||
a3bab2619c
|
|||
70815fa1e3
|
|||
ebfd3c636d | |||
a3da71668f
|
|||
fd893fbf89
|
|||
17296ade19
|
|||
85476162cf
|
|||
837b412ef0
|
|||
02098977a5
|
|||
20584b45ca
|
|||
105c598c53
|
|||
c65a024d97
|
|||
041959e546
|
|||
cc1ec56b33
|
|||
0a59f3258a | |||
62df510147
|
|||
5b8cc30012
|
|||
3c8f9f9f07
|
|||
46eab35290
|
|||
7db2190ec3
|
|||
77be96e8de
|
|||
6eb3cbbd84
|
|||
c0e70daf58
|
|||
eca7e09d19
|
|||
98e2a73aa2
|
|||
05eb9d44ef
|
|||
ba22618449 | |||
9ecc1f1ff2 | |||
240004b814
|
|||
79791a75bd
|
|||
b553cdc2ec
|
|||
e46de3421e
|
|||
fd95c86294
|
|||
f117c8c4de
|
|||
784564a20e
|
|||
e3d2d88538
|
|||
4969d6c33c
|
|||
581b51c61c
|
|||
b5bea3e1c6
|
|||
defd7609e7
|
|||
b9774c4c9f
|
|||
4fdfb20946
|
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@ -27,7 +27,7 @@ jobs:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: 1.60.0
|
||||
toolchain: 1.61.0
|
||||
override: true
|
||||
profile: minimal
|
||||
- uses: actions-rs/cargo@v1
|
||||
|
64
CHANGELOG.md
64
CHANGELOG.md
@ -8,6 +8,70 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
# [unreleased]
|
||||
|
||||
# [v0.7.0-beta.1] 2023-08-28
|
||||
|
||||
- Bump `zerocopy` dependency to v0.7.0
|
||||
|
||||
## Changed
|
||||
|
||||
- The `Tlv` and `Lv` API return `&[u8]` instead of `Option<&[u8]>`.
|
||||
- `ByteConversionError` error variants `ToSliceTooSmall` and `FromSliceTooSmall` are struct
|
||||
variants now. `SizeMissmatch` was removed appropriately.
|
||||
- `UnsignedByteFieldError` error variants `ValueTooLargeForWidth` and `InvalidWidth` are struct
|
||||
variants now.
|
||||
- `TimestampError` error variant `InvalidTimeCode` is struct variant now.
|
||||
|
||||
## Added
|
||||
|
||||
- Added `raw_data` API for `Tlv` and `Lv` to retrieve the whole `Lv`/`Tlv` slice if the object
|
||||
was created from a raw bytestream.
|
||||
- Added `MsgToUserTlv` helper class which wraps a regular `Tlv` and adds some useful functionality.
|
||||
- `UnsignedByteField` and `GenericUnsignedByteField` `new` methods are `const` now.
|
||||
- `PduError` variants which contained a tuple variant with multiple fields were converted to a
|
||||
struct variant.
|
||||
|
||||
# Added
|
||||
|
||||
- Added `pdu_datafield_len` getter function for `PduHeader`
|
||||
|
||||
## Removed
|
||||
|
||||
- `SizeMissmatch` because it is not required for the `ByteConversionError` error enumeration
|
||||
anymore.
|
||||
|
||||
# [v0.7.0-beta.0] 2023-08-16
|
||||
|
||||
- Moved MSRV from v1.60 to v1.61.
|
||||
|
||||
## Changed
|
||||
|
||||
- `PusPacket` trait: `user_data` now returns `&[u8]` instead of `Option<&[u8]>`. Empty user data
|
||||
can simply be an empty slice.
|
||||
- Moved ECSS TC components from `tc` to `ecss.tc`.
|
||||
- Moved ECSS TM components from `tm` to `ecss.tm`.
|
||||
- Converted `PusTc` class to more specialized `PusTcCreator` and `PusTcReader`
|
||||
classes. The old `PusTc` class is deprecated now.
|
||||
- Converted `PusTm` class to more specialized `PusTmCreator` and `PusTmReader`
|
||||
classes. The old `PusTm` class is deprecated now.
|
||||
- Implement `Display` and `Error` for `StdTimestampError` properly.
|
||||
- Remove some redundant `Error` suffixes for enum error variants.
|
||||
- `CommonPduConfig`: `new_with_defaults` replaced by `new_with_byte_fields`.
|
||||
|
||||
## Added
|
||||
|
||||
- `source_data` and `app_data` API provided for PUS TM and PUS TC reader classes. These simply
|
||||
call `user_data` but are also in line with the PUS packet standard names for those fields.
|
||||
- Added new marker trait `IsPusTelemetry` implemented by `PusTmCreator` and `PusTmReader`.
|
||||
- Added new marker trait `IsPusTelecommand` implemented by `PusTcCreator` and `PusTcReader`.
|
||||
- `metadata_param` getter method for the `MetadataPdu` object.
|
||||
- `Default` impl for CFDP `ChecksumType`
|
||||
- `Default` impl for CFDP `CommonPduConfig`
|
||||
|
||||
## Fixed
|
||||
|
||||
- All `MetadataGenericParam` fields are now public.
|
||||
- New setter method `set_source_and_dest_id` for `CommonPduConfig`.
|
||||
|
||||
# [v0.6.0] 2023-07-06
|
||||
|
||||
## Added
|
||||
|
17
Cargo.toml
17
Cargo.toml
@ -1,8 +1,8 @@
|
||||
[package]
|
||||
name = "spacepackets"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0-beta.1"
|
||||
edition = "2021"
|
||||
rust-version = "1.60"
|
||||
rust-version = "1.61"
|
||||
authors = ["Robin Mueller <muellerr@irs.uni-stuttgart.de>"]
|
||||
description = "Generic implementations for various CCSDS and ECSS packet standards"
|
||||
homepage = "https://egit.irs.uni-stuttgart.de/rust/spacepackets"
|
||||
@ -13,12 +13,19 @@ categories = ["aerospace", "aerospace::space-protocols", "no-std", "hardware-sup
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
zerocopy = "0.6"
|
||||
crc = "3"
|
||||
delegate = ">=0.8, <0.11"
|
||||
|
||||
[dependencies.zerocopy]
|
||||
version = "0.7"
|
||||
features = ["derive"]
|
||||
|
||||
[dependencies.thiserror]
|
||||
version = "1"
|
||||
optional = true
|
||||
|
||||
[dependencies.num_enum]
|
||||
version = "0.6"
|
||||
version = ">0.5, <=0.7"
|
||||
default-features = false
|
||||
|
||||
[dependencies.serde]
|
||||
@ -40,7 +47,7 @@ version = "1"
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = ["chrono/std", "chrono/clock", "alloc"]
|
||||
std = ["chrono/std", "chrono/clock", "alloc", "thiserror"]
|
||||
serde = ["dep:serde", "chrono/serde"]
|
||||
alloc = ["postcard/alloc", "chrono/alloc"]
|
||||
|
||||
|
@ -13,6 +13,10 @@ Checklist for new releases
|
||||
6. Wait for CI/CD results for EGit and Github. These also check cross-compilation for bare-metal
|
||||
targets.
|
||||
|
||||
# Release
|
||||
|
||||
1. `cargo publish`
|
||||
|
||||
# Post-Release
|
||||
|
||||
1. Create a new release on `EGit` based on the release branch.
|
||||
|
115
src/cfdp/lv.rs
115
src/cfdp/lv.rs
@ -1,6 +1,6 @@
|
||||
//! Generic CFDP length-value (LV) abstraction as specified in CFDP 5.1.8.
|
||||
use crate::cfdp::TlvLvError;
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use core::str::Utf8Error;
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
@ -11,14 +11,26 @@ pub const MIN_LV_LEN: usize = 1;
|
||||
|
||||
/// Generic CFDP length-value (LV) abstraction as specified in CFDP 5.1.8.
|
||||
///
|
||||
/// Please note that this class is zero-copy and does not generate a copy of the value data for
|
||||
/// both the regular [Self::new] constructor and the [Self::from_bytes] constructor.
|
||||
///
|
||||
/// # Lifetimes
|
||||
/// * `data`: If the LV is generated from a raw bytestream, this will be the lifetime of
|
||||
/// the raw bytestream. If the LV is generated from a raw slice or a similar data reference,
|
||||
/// this will be the lifetime of that data reference.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Copy, Clone, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct Lv<'data> {
|
||||
data: Option<&'data [u8]>,
|
||||
data: &'data [u8],
|
||||
// If the LV was generated from a raw bytestream, this will contain the start of the
|
||||
// full LV.
|
||||
pub(crate) raw_data: Option<&'data [u8]>,
|
||||
}
|
||||
|
||||
impl PartialEq for Lv<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.data == other.data
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn generic_len_check_data_serialization(
|
||||
@ -27,10 +39,10 @@ pub(crate) fn generic_len_check_data_serialization(
|
||||
min_overhead: usize,
|
||||
) -> Result<(), ByteConversionError> {
|
||||
if buf.len() < data_len + min_overhead {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: data_len + min_overhead,
|
||||
}));
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -40,10 +52,10 @@ pub(crate) fn generic_len_check_deserialization(
|
||||
min_overhead: usize,
|
||||
) -> Result<(), ByteConversionError> {
|
||||
if buf.len() < min_overhead {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: min_overhead,
|
||||
}));
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -53,12 +65,18 @@ impl<'data> Lv<'data> {
|
||||
if data.len() > u8::MAX as usize {
|
||||
return Err(TlvLvError::DataTooLarge(data.len()));
|
||||
}
|
||||
Ok(Lv { data: Some(data) })
|
||||
Ok(Lv {
|
||||
data,
|
||||
raw_data: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a LV with an empty value field.
|
||||
pub fn new_empty() -> Lv<'data> {
|
||||
Lv { data: None }
|
||||
Lv {
|
||||
data: &[],
|
||||
raw_data: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper function to build a string LV. This is especially useful for the file or directory
|
||||
@ -70,16 +88,14 @@ impl<'data> Lv<'data> {
|
||||
/// Helper function to build a string LV. This is especially useful for the file or directory
|
||||
/// path LVs
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
||||
pub fn new_from_string(string: &'data String) -> Result<Lv<'data>, TlvLvError> {
|
||||
Self::new(string.as_bytes())
|
||||
}
|
||||
|
||||
/// Returns the length of the value part, not including the length byte.
|
||||
pub fn len_value(&self) -> usize {
|
||||
if self.data.is_none() {
|
||||
return 0;
|
||||
}
|
||||
self.data.unwrap().len()
|
||||
self.data.len()
|
||||
}
|
||||
|
||||
/// Returns the full raw length, including the length byte.
|
||||
@ -89,18 +105,26 @@ impl<'data> Lv<'data> {
|
||||
|
||||
/// Checks whether the value field is empty.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.data.is_none()
|
||||
self.data.len() == 0
|
||||
}
|
||||
|
||||
pub fn value(&self) -> Option<&[u8]> {
|
||||
pub fn value(&self) -> &[u8] {
|
||||
self.data
|
||||
}
|
||||
|
||||
/// If the LV was generated from a raw bytestream using [Self::from_bytes], the raw start
|
||||
/// of the LV can be retrieved with this method.
|
||||
pub fn raw_data(&self) -> Option<&[u8]> {
|
||||
self.raw_data
|
||||
}
|
||||
|
||||
/// Convenience function to extract the value as a [str]. This is useful if the LV is
|
||||
/// known to contain a [str], for example being a file name.
|
||||
pub fn value_as_str(&self) -> Option<Result<&'data str, Utf8Error>> {
|
||||
self.data?;
|
||||
Some(core::str::from_utf8(self.data.unwrap()))
|
||||
if self.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(core::str::from_utf8(self.data))
|
||||
}
|
||||
|
||||
/// Writes the LV to a raw buffer. Please note that the first byte will contain the length
|
||||
@ -117,15 +141,14 @@ impl<'data> Lv<'data> {
|
||||
}
|
||||
|
||||
pub(crate) fn write_to_be_bytes_no_len_check(&self, buf: &mut [u8]) -> usize {
|
||||
if self.data.is_none() {
|
||||
if self.is_empty() {
|
||||
buf[0] = 0;
|
||||
return MIN_LV_LEN;
|
||||
}
|
||||
let data = self.data.unwrap();
|
||||
// Length check in constructor ensures the length always has a valid value.
|
||||
buf[0] = data.len() as u8;
|
||||
buf[MIN_LV_LEN..data.len() + MIN_LV_LEN].copy_from_slice(data);
|
||||
MIN_LV_LEN + data.len()
|
||||
buf[0] = self.data.len() as u8;
|
||||
buf[MIN_LV_LEN..self.data.len() + MIN_LV_LEN].copy_from_slice(self.data);
|
||||
MIN_LV_LEN + self.data.len()
|
||||
}
|
||||
|
||||
pub(crate) fn from_be_bytes_no_len_check(
|
||||
@ -133,11 +156,10 @@ impl<'data> Lv<'data> {
|
||||
) -> Result<Lv<'data>, ByteConversionError> {
|
||||
let value_len = buf[0] as usize;
|
||||
generic_len_check_deserialization(buf, value_len + MIN_LV_LEN)?;
|
||||
let mut data = None;
|
||||
if value_len > 0 {
|
||||
data = Some(&buf[MIN_LV_LEN..MIN_LV_LEN + value_len])
|
||||
}
|
||||
Ok(Self { data })
|
||||
Ok(Self {
|
||||
data: &buf[MIN_LV_LEN..MIN_LV_LEN + value_len],
|
||||
raw_data: Some(buf),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@ -154,8 +176,8 @@ pub mod tests {
|
||||
let lv_res = Lv::new(&lv_data);
|
||||
assert!(lv_res.is_ok());
|
||||
let lv = lv_res.unwrap();
|
||||
assert!(lv.value().is_some());
|
||||
let val = lv.value().unwrap();
|
||||
assert!(lv.value().len() > 0);
|
||||
let val = lv.value();
|
||||
assert_eq!(val[0], 1);
|
||||
assert_eq!(val[1], 2);
|
||||
assert_eq!(val[2], 3);
|
||||
@ -171,7 +193,6 @@ pub mod tests {
|
||||
assert_eq!(lv_empty.len_value(), 0);
|
||||
assert_eq!(lv_empty.len_full(), 1);
|
||||
assert!(lv_empty.is_empty());
|
||||
assert_eq!(lv_empty.value(), None);
|
||||
let mut buf: [u8; 4] = [0xff; 4];
|
||||
let res = lv_empty.write_to_be_bytes(&mut buf);
|
||||
assert!(res.is_ok());
|
||||
@ -210,10 +231,11 @@ pub mod tests {
|
||||
assert!(lv.is_ok());
|
||||
let lv = lv.unwrap();
|
||||
assert!(!lv.is_empty());
|
||||
assert!(lv.value().is_some());
|
||||
assert_eq!(lv.len_value(), 4);
|
||||
assert_eq!(lv.len_full(), 5);
|
||||
let val = lv.value().unwrap();
|
||||
assert!(lv.raw_data().is_some());
|
||||
assert_eq!(lv.raw_data().unwrap(), buf);
|
||||
let val = lv.value();
|
||||
assert_eq!(val[0], 1);
|
||||
assert_eq!(val[1], 2);
|
||||
assert_eq!(val[2], 3);
|
||||
@ -227,7 +249,6 @@ pub mod tests {
|
||||
assert!(lv_empty.is_ok());
|
||||
let lv_empty = lv_empty.unwrap();
|
||||
assert!(lv_empty.is_empty());
|
||||
assert!(lv_empty.value().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -251,9 +272,9 @@ pub mod tests {
|
||||
let res = lv.write_to_be_bytes(&mut buf);
|
||||
assert!(res.is_err());
|
||||
let error = res.unwrap_err();
|
||||
if let ByteConversionError::ToSliceTooSmall(missmatch) = error {
|
||||
assert_eq!(missmatch.expected, 5);
|
||||
assert_eq!(missmatch.found, 3);
|
||||
if let ByteConversionError::ToSliceTooSmall { found, expected } = error {
|
||||
assert_eq!(expected, 5);
|
||||
assert_eq!(found, 3);
|
||||
} else {
|
||||
panic!("invalid error {}", error);
|
||||
}
|
||||
@ -266,9 +287,9 @@ pub mod tests {
|
||||
let res = Lv::from_bytes(&buf);
|
||||
assert!(res.is_err());
|
||||
let error = res.unwrap_err();
|
||||
if let ByteConversionError::FromSliceTooSmall(missmatch) = error {
|
||||
assert_eq!(missmatch.found, 3);
|
||||
assert_eq!(missmatch.expected, 5);
|
||||
if let ByteConversionError::FromSliceTooSmall { found, expected } = error {
|
||||
assert_eq!(found, 3);
|
||||
assert_eq!(expected, 5);
|
||||
} else {
|
||||
panic!("invalid error {}", error);
|
||||
}
|
||||
@ -281,14 +302,14 @@ pub mod tests {
|
||||
let res = res.unwrap();
|
||||
assert_eq!(res, 8 + 1);
|
||||
assert_eq!(buf[0], 8);
|
||||
assert_eq!(buf[1], 't' as u8);
|
||||
assert_eq!(buf[2], 'e' as u8);
|
||||
assert_eq!(buf[3], 's' as u8);
|
||||
assert_eq!(buf[4], 't' as u8);
|
||||
assert_eq!(buf[5], '.' as u8);
|
||||
assert_eq!(buf[6], 'b' as u8);
|
||||
assert_eq!(buf[7], 'i' as u8);
|
||||
assert_eq!(buf[8], 'n' as u8);
|
||||
assert_eq!(buf[1], b't');
|
||||
assert_eq!(buf[2], b'e');
|
||||
assert_eq!(buf[3], b's');
|
||||
assert_eq!(buf[4], b't');
|
||||
assert_eq!(buf[5], b'.');
|
||||
assert_eq!(buf[6], b'b');
|
||||
assert_eq!(buf[7], b'i');
|
||||
assert_eq!(buf[8], b'n');
|
||||
}
|
||||
#[test]
|
||||
fn test_str_helper() {
|
||||
|
@ -134,6 +134,12 @@ pub enum ChecksumType {
|
||||
NullChecksum = 15,
|
||||
}
|
||||
|
||||
impl Default for ChecksumType {
|
||||
fn default() -> Self {
|
||||
Self::NullChecksum
|
||||
}
|
||||
}
|
||||
|
||||
pub const NULL_CHECKSUM_U32: [u8; 4] = [0; 4];
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
|
@ -4,7 +4,7 @@ use crate::cfdp::pdu::{
|
||||
};
|
||||
use crate::cfdp::tlv::EntityIdTlv;
|
||||
use crate::cfdp::{ConditionCode, CrcFlag, LargeFileFlag};
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@ -69,10 +69,10 @@ impl EofPdu {
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||
let expected_len = self.written_len();
|
||||
if buf.len() < expected_len {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: expected_len,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
let mut current_idx = self.pdu_header.write_to_bytes(buf)?;
|
||||
@ -106,13 +106,16 @@ impl EofPdu {
|
||||
}
|
||||
generic_length_checks_pdu_deserialization(buf, min_expected_len, full_len_without_crc)?;
|
||||
let directive_type = FileDirectiveType::try_from(buf[current_idx]).map_err(|_| {
|
||||
PduError::InvalidDirectiveType((buf[current_idx], FileDirectiveType::EofPdu))
|
||||
PduError::InvalidDirectiveType {
|
||||
found: buf[current_idx],
|
||||
expected: Some(FileDirectiveType::EofPdu),
|
||||
}
|
||||
})?;
|
||||
if directive_type != FileDirectiveType::EofPdu {
|
||||
return Err(PduError::WrongDirectiveType((
|
||||
directive_type,
|
||||
FileDirectiveType::EofPdu,
|
||||
)));
|
||||
return Err(PduError::WrongDirectiveType {
|
||||
found: directive_type,
|
||||
expected: FileDirectiveType::EofPdu,
|
||||
});
|
||||
}
|
||||
current_idx += 1;
|
||||
let condition_code = ConditionCode::try_from((buf[current_idx] >> 4) & 0b1111)
|
||||
|
@ -3,7 +3,7 @@ use crate::cfdp::pdu::{
|
||||
PduError, PduHeader,
|
||||
};
|
||||
use crate::cfdp::{CrcFlag, LargeFileFlag, PduType, SegmentMetadataFlag};
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
@ -48,10 +48,10 @@ impl<'seg_meta> SegmentMetadata<'seg_meta> {
|
||||
|
||||
pub(crate) fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
if buf.len() < self.written_len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: self.written_len(),
|
||||
}));
|
||||
});
|
||||
}
|
||||
buf[0] = ((self.record_continuation_state as u8) << 6)
|
||||
| self.metadata.map_or(0, |meta| meta.len() as u8);
|
||||
@ -63,10 +63,10 @@ impl<'seg_meta> SegmentMetadata<'seg_meta> {
|
||||
|
||||
pub(crate) fn from_bytes(buf: &'seg_meta [u8]) -> Result<Self, ByteConversionError> {
|
||||
if buf.is_empty() {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: 2,
|
||||
}));
|
||||
});
|
||||
}
|
||||
let mut metadata = None;
|
||||
let seg_metadata_len = (buf[0] & 0b111111) as usize;
|
||||
@ -165,10 +165,10 @@ impl<'seg_meta, 'file_data> FileDataPdu<'seg_meta, 'file_data> {
|
||||
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||
if buf.len() < self.written_len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: self.written_len(),
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
let mut current_idx = self.pdu_header.write_to_bytes(buf)?;
|
||||
@ -207,10 +207,10 @@ impl<'seg_meta, 'file_data> FileDataPdu<'seg_meta, 'file_data> {
|
||||
let (fss, offset) = read_fss_field(pdu_header.pdu_conf.file_flag, &buf[current_idx..]);
|
||||
current_idx += fss;
|
||||
if current_idx > full_len_without_crc {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: current_idx,
|
||||
expected: full_len_without_crc,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
Ok(Self {
|
||||
@ -235,7 +235,7 @@ mod tests {
|
||||
let dest_id = UbfU8::new(2);
|
||||
let transaction_seq_num = UbfU8::new(3);
|
||||
let common_conf =
|
||||
CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_seq_num).unwrap();
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_seq_num).unwrap();
|
||||
let pdu_header = PduHeader::new_for_file_data_default(common_conf, 0);
|
||||
let file_data: [u8; 4] = [1, 2, 3, 4];
|
||||
let fd_pdu = FileDataPdu::new_no_seg_metadata(pdu_header, 10, &file_data);
|
||||
@ -254,7 +254,7 @@ mod tests {
|
||||
let dest_id = UbfU8::new(2);
|
||||
let transaction_seq_num = UbfU8::new(3);
|
||||
let common_conf =
|
||||
CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_seq_num).unwrap();
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_seq_num).unwrap();
|
||||
let pdu_header = PduHeader::new_for_file_data_default(common_conf, 0);
|
||||
let file_data: [u8; 4] = [1, 2, 3, 4];
|
||||
let fd_pdu = FileDataPdu::new_no_seg_metadata(pdu_header, 10, &file_data);
|
||||
@ -289,7 +289,7 @@ mod tests {
|
||||
let dest_id = UbfU8::new(2);
|
||||
let transaction_seq_num = UbfU8::new(3);
|
||||
let common_conf =
|
||||
CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_seq_num).unwrap();
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_seq_num).unwrap();
|
||||
let pdu_header = PduHeader::new_for_file_data_default(common_conf, 0);
|
||||
let file_data: [u8; 4] = [1, 2, 3, 4];
|
||||
let fd_pdu = FileDataPdu::new_no_seg_metadata(pdu_header, 10, &file_data);
|
||||
@ -307,7 +307,7 @@ mod tests {
|
||||
let dest_id = UbfU8::new(2);
|
||||
let transaction_seq_num = UbfU8::new(3);
|
||||
let common_conf =
|
||||
CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_seq_num).unwrap();
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_seq_num).unwrap();
|
||||
let pdu_header = PduHeader::new_for_file_data(
|
||||
common_conf,
|
||||
0,
|
||||
@ -372,7 +372,7 @@ mod tests {
|
||||
let dest_id = UbfU8::new(2);
|
||||
let transaction_seq_num = UbfU8::new(3);
|
||||
let common_conf =
|
||||
CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_seq_num).unwrap();
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_seq_num).unwrap();
|
||||
let pdu_header = PduHeader::new_for_file_data(
|
||||
common_conf,
|
||||
0,
|
||||
|
@ -3,7 +3,7 @@ use crate::cfdp::pdu::{
|
||||
};
|
||||
use crate::cfdp::tlv::{EntityIdTlv, Tlv, TlvType, TlvTypeField};
|
||||
use crate::cfdp::{ConditionCode, CrcFlag, PduType, TlvLvError};
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
@ -136,10 +136,10 @@ impl<'fs_responses> FinishedPdu<'fs_responses> {
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||
let expected_len = self.written_len();
|
||||
if buf.len() < expected_len {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: expected_len,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
|
||||
@ -170,13 +170,16 @@ impl<'fs_responses> FinishedPdu<'fs_responses> {
|
||||
let min_expected_len = current_idx + 2;
|
||||
generic_length_checks_pdu_deserialization(buf, min_expected_len, full_len_without_crc)?;
|
||||
let directive_type = FileDirectiveType::try_from(buf[current_idx]).map_err(|_| {
|
||||
PduError::InvalidDirectiveType((buf[current_idx], FileDirectiveType::FinishedPdu))
|
||||
PduError::InvalidDirectiveType {
|
||||
found: buf[current_idx],
|
||||
expected: Some(FileDirectiveType::FinishedPdu),
|
||||
}
|
||||
})?;
|
||||
if directive_type != FileDirectiveType::FinishedPdu {
|
||||
return Err(PduError::WrongDirectiveType((
|
||||
directive_type,
|
||||
FileDirectiveType::FinishedPdu,
|
||||
)));
|
||||
return Err(PduError::WrongDirectiveType {
|
||||
found: directive_type,
|
||||
expected: FileDirectiveType::FinishedPdu,
|
||||
});
|
||||
}
|
||||
current_idx += 1;
|
||||
let condition_code = ConditionCode::try_from((buf[current_idx] >> 4) & 0b1111)
|
||||
|
@ -5,18 +5,18 @@ use crate::cfdp::pdu::{
|
||||
};
|
||||
use crate::cfdp::tlv::Tlv;
|
||||
use crate::cfdp::{ChecksumType, CrcFlag, LargeFileFlag, PduType};
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
#[cfg(feature = "alloc")]
|
||||
use alloc::vec::Vec;
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct MetadataGenericParams {
|
||||
closure_requested: bool,
|
||||
checksum_type: ChecksumType,
|
||||
file_size: u64,
|
||||
pub closure_requested: bool,
|
||||
pub checksum_type: ChecksumType,
|
||||
pub file_size: u64,
|
||||
}
|
||||
|
||||
impl MetadataGenericParams {
|
||||
@ -145,6 +145,10 @@ impl<'src_name, 'dest_name, 'opts> MetadataPdu<'src_name, 'dest_name, 'opts> {
|
||||
pdu
|
||||
}
|
||||
|
||||
pub fn metadata_params(&self) -> &MetadataGenericParams {
|
||||
&self.metadata_params
|
||||
}
|
||||
|
||||
pub fn src_file_name(&self) -> Lv<'src_name> {
|
||||
self.src_file_name
|
||||
}
|
||||
@ -197,10 +201,10 @@ impl<'src_name, 'dest_name, 'opts> MetadataPdu<'src_name, 'dest_name, 'opts> {
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||
let expected_len = self.written_len();
|
||||
if buf.len() < expected_len {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: expected_len,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
|
||||
@ -244,13 +248,16 @@ impl<'src_name, 'dest_name, 'opts> MetadataPdu<'src_name, 'dest_name, 'opts> {
|
||||
}
|
||||
generic_length_checks_pdu_deserialization(buf, min_expected_len, full_len_without_crc)?;
|
||||
let directive_type = FileDirectiveType::try_from(buf[current_idx]).map_err(|_| {
|
||||
PduError::InvalidDirectiveType((buf[current_idx], FileDirectiveType::MetadataPdu))
|
||||
PduError::InvalidDirectiveType {
|
||||
found: buf[current_idx],
|
||||
expected: Some(FileDirectiveType::MetadataPdu),
|
||||
}
|
||||
})?;
|
||||
if directive_type != FileDirectiveType::MetadataPdu {
|
||||
return Err(PduError::WrongDirectiveType((
|
||||
directive_type,
|
||||
FileDirectiveType::MetadataPdu,
|
||||
)));
|
||||
return Err(PduError::WrongDirectiveType {
|
||||
found: directive_type,
|
||||
expected: FileDirectiveType::MetadataPdu,
|
||||
});
|
||||
}
|
||||
current_idx += 1;
|
||||
let (fss_len, file_size) =
|
||||
|
@ -1,8 +1,8 @@
|
||||
//! CFDP Packet Data Unit (PDU) support.
|
||||
use crate::cfdp::*;
|
||||
use crate::util::{UnsignedByteField, UnsignedEnum};
|
||||
use crate::util::{UnsignedByteField, UnsignedByteFieldU8, UnsignedEnum};
|
||||
use crate::ByteConversionError;
|
||||
use crate::CRC_CCITT_FALSE;
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use core::fmt::{Display, Formatter};
|
||||
#[cfg(feature = "std")]
|
||||
use std::error::Error;
|
||||
@ -35,16 +35,19 @@ pub enum PduError {
|
||||
InvalidEntityLen(u8),
|
||||
/// Invalid length for the entity ID detected. Only the values 1, 2, 4 and 8 are supported.
|
||||
InvalidTransactionSeqNumLen(u8),
|
||||
/// The first entry will be the source entity ID length, the second one the destination entity
|
||||
/// ID length.
|
||||
SourceDestIdLenMissmatch((usize, usize)),
|
||||
/// The first tuple entry will be the found directive type, the second entry the expected entry
|
||||
/// type.
|
||||
WrongDirectiveType((FileDirectiveType, FileDirectiveType)),
|
||||
SourceDestIdLenMissmatch {
|
||||
src_id_len: usize,
|
||||
dest_id_len: usize,
|
||||
},
|
||||
WrongDirectiveType {
|
||||
found: FileDirectiveType,
|
||||
expected: FileDirectiveType,
|
||||
},
|
||||
/// The directive type field contained a value not in the range of permitted values.
|
||||
/// The first tuple entry will be the found raw number, the second entry the expected entry
|
||||
/// type.
|
||||
InvalidDirectiveType((u8, FileDirectiveType)),
|
||||
InvalidDirectiveType {
|
||||
found: u8,
|
||||
expected: Option<FileDirectiveType>,
|
||||
},
|
||||
/// Invalid condition code. Contains the raw detected value.
|
||||
InvalidConditionCode(u8),
|
||||
/// Invalid checksum type which is not part of the checksums listed in the
|
||||
@ -80,10 +83,13 @@ impl Display for PduError {
|
||||
"cfdp version missmatch, found {raw}, expected {CFDP_VERSION_2}"
|
||||
)
|
||||
}
|
||||
PduError::SourceDestIdLenMissmatch((src_len, dest_len)) => {
|
||||
PduError::SourceDestIdLenMissmatch {
|
||||
src_id_len,
|
||||
dest_id_len,
|
||||
} => {
|
||||
write!(
|
||||
f,
|
||||
"missmatch of PDU source length {src_len} and destination length {dest_len}"
|
||||
"missmatch of PDU source length {src_id_len} and destination length {dest_id_len}"
|
||||
)
|
||||
}
|
||||
PduError::ByteConversionError(e) => {
|
||||
@ -92,17 +98,16 @@ impl Display for PduError {
|
||||
PduError::FileSizeTooLarge(value) => {
|
||||
write!(f, "file size value {value} exceeds allowed 32 bit width")
|
||||
}
|
||||
PduError::WrongDirectiveType((found, expected)) => {
|
||||
PduError::WrongDirectiveType { found, expected } => {
|
||||
write!(f, "found directive type {found:?}, expected {expected:?}")
|
||||
}
|
||||
PduError::InvalidConditionCode(raw_code) => {
|
||||
write!(f, "found invalid condition code with raw value {raw_code}")
|
||||
}
|
||||
PduError::InvalidDirectiveType((found, expected)) => {
|
||||
PduError::InvalidDirectiveType { found, expected } => {
|
||||
write!(
|
||||
f,
|
||||
"invalid directive type value {found}, expected {expected:?} ({})",
|
||||
*expected as u8
|
||||
"invalid directive type value {found}, expected {expected:?}"
|
||||
)
|
||||
}
|
||||
PduError::InvalidChecksumType(checksum_type) => {
|
||||
@ -168,22 +173,8 @@ impl CommonPduConfig {
|
||||
crc_flag: CrcFlag,
|
||||
direction: Direction,
|
||||
) -> Result<Self, PduError> {
|
||||
let source_id = source_id.into();
|
||||
let dest_id = dest_id.into();
|
||||
let (source_id, dest_id) = Self::source_dest_id_check(source_id, dest_id)?;
|
||||
let transaction_seq_num = transaction_seq_num.into();
|
||||
if source_id.size() != dest_id.size() {
|
||||
return Err(PduError::SourceDestIdLenMissmatch((
|
||||
source_id.size(),
|
||||
dest_id.size(),
|
||||
)));
|
||||
}
|
||||
if source_id.size() != 1
|
||||
&& source_id.size() != 2
|
||||
&& source_id.size() != 4
|
||||
&& source_id.size() != 8
|
||||
{
|
||||
return Err(PduError::InvalidEntityLen(source_id.size() as u8));
|
||||
}
|
||||
if transaction_seq_num.size() != 1
|
||||
&& transaction_seq_num.size() != 2
|
||||
&& transaction_seq_num.size() != 4
|
||||
@ -204,7 +195,7 @@ impl CommonPduConfig {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn new_with_defaults(
|
||||
pub fn new_with_byte_fields(
|
||||
source_id: impl Into<UnsignedByteField>,
|
||||
dest_id: impl Into<UnsignedByteField>,
|
||||
transaction_seq_num: impl Into<UnsignedByteField>,
|
||||
@ -224,11 +215,62 @@ impl CommonPduConfig {
|
||||
self.source_entity_id
|
||||
}
|
||||
|
||||
fn source_dest_id_check(
|
||||
source_id: impl Into<UnsignedByteField>,
|
||||
dest_id: impl Into<UnsignedByteField>,
|
||||
) -> Result<(UnsignedByteField, UnsignedByteField), PduError> {
|
||||
let source_id = source_id.into();
|
||||
let dest_id = dest_id.into();
|
||||
if source_id.size() != dest_id.size() {
|
||||
return Err(PduError::SourceDestIdLenMissmatch {
|
||||
src_id_len: source_id.size(),
|
||||
dest_id_len: dest_id.size(),
|
||||
});
|
||||
}
|
||||
if source_id.size() != 1
|
||||
&& source_id.size() != 2
|
||||
&& source_id.size() != 4
|
||||
&& source_id.size() != 8
|
||||
{
|
||||
return Err(PduError::InvalidEntityLen(source_id.size() as u8));
|
||||
}
|
||||
Ok((source_id, dest_id))
|
||||
}
|
||||
|
||||
pub fn set_source_and_dest_id(
|
||||
&mut self,
|
||||
source_id: impl Into<UnsignedByteField>,
|
||||
dest_id: impl Into<UnsignedByteField>,
|
||||
) -> Result<(), PduError> {
|
||||
let (source_id, dest_id) = Self::source_dest_id_check(source_id, dest_id)?;
|
||||
self.source_entity_id = source_id;
|
||||
self.dest_entity_id = dest_id;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn dest_id(&self) -> UnsignedByteField {
|
||||
self.dest_entity_id
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CommonPduConfig {
|
||||
/// The defaults for the source ID, destination ID and the transaction sequence number is the
|
||||
/// [UnsignedByteFieldU8] with an intitial value of 0
|
||||
fn default() -> Self {
|
||||
// The new function can not fail for these input parameters.
|
||||
Self::new(
|
||||
UnsignedByteFieldU8::new(0),
|
||||
UnsignedByteFieldU8::new(0),
|
||||
UnsignedByteFieldU8::new(0),
|
||||
TransmissionMode::Acknowledged,
|
||||
LargeFileFlag::Normal,
|
||||
CrcFlag::NoCrc,
|
||||
Direction::TowardsReceiver,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub const FIXED_HEADER_LEN: usize = 4;
|
||||
|
||||
/// Abstraction for the PDU header common to all CFDP PDUs.
|
||||
@ -303,6 +345,10 @@ impl PduHeader {
|
||||
+ self.pdu_conf.dest_entity_id.size()
|
||||
}
|
||||
|
||||
pub fn pdu_datafield_len(&self) -> usize {
|
||||
self.pdu_datafield_len.into()
|
||||
}
|
||||
|
||||
/// Returns the full length of the PDU when written to a raw buffer, which is the header length
|
||||
/// plus the PDU datafield length.
|
||||
pub fn pdu_len(&self) -> usize {
|
||||
@ -313,20 +359,20 @@ impl PduHeader {
|
||||
// Internal note: There is currently no way to pass a PDU configuration like this, but
|
||||
// this check is still kept for defensive programming.
|
||||
if self.pdu_conf.source_entity_id.size() != self.pdu_conf.dest_entity_id.size() {
|
||||
return Err(PduError::SourceDestIdLenMissmatch((
|
||||
self.pdu_conf.source_entity_id.size(),
|
||||
self.pdu_conf.dest_entity_id.size(),
|
||||
)));
|
||||
return Err(PduError::SourceDestIdLenMissmatch {
|
||||
src_id_len: self.pdu_conf.source_entity_id.size(),
|
||||
dest_id_len: self.pdu_conf.dest_entity_id.size(),
|
||||
});
|
||||
}
|
||||
if buf.len()
|
||||
< FIXED_HEADER_LEN
|
||||
+ self.pdu_conf.source_entity_id.size()
|
||||
+ self.pdu_conf.transaction_seq_num.size()
|
||||
{
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: FIXED_HEADER_LEN,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
let mut current_idx = 0;
|
||||
@ -367,10 +413,10 @@ impl PduHeader {
|
||||
/// flag is not set, it will simply return the PDU length.
|
||||
pub fn verify_length_and_checksum(&self, buf: &[u8]) -> Result<usize, PduError> {
|
||||
if buf.len() < self.pdu_len() {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: self.pdu_len(),
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
if self.pdu_conf.crc_flag == CrcFlag::WithCrc {
|
||||
@ -397,10 +443,10 @@ impl PduHeader {
|
||||
pub fn from_bytes(buf: &[u8]) -> Result<(Self, usize), PduError> {
|
||||
if buf.len() < FIXED_HEADER_LEN {
|
||||
return Err(PduError::ByteConversionError(
|
||||
ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: FIXED_HEADER_LEN,
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
let cfdp_version_raw = (buf[0] >> 5) & 0b111;
|
||||
@ -435,10 +481,10 @@ impl PduHeader {
|
||||
));
|
||||
}
|
||||
if buf.len() < (4 + 2 * expected_len_entity_ids + expected_len_seq_num) {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: 4 + 2 * expected_len_entity_ids + expected_len_seq_num,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
let mut current_idx = 4;
|
||||
@ -534,17 +580,17 @@ pub(crate) fn generic_length_checks_pdu_deserialization(
|
||||
) -> Result<(), ByteConversionError> {
|
||||
// Buffer too short to hold additional expected minimum datasize.
|
||||
if buf.len() < min_expected_len {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: min_expected_len,
|
||||
}));
|
||||
});
|
||||
}
|
||||
// This can happen if the PDU datafield length value is invalid.
|
||||
if full_len_without_crc < min_expected_len {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: full_len_without_crc,
|
||||
expected: min_expected_len,
|
||||
}));
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -574,8 +620,9 @@ mod tests {
|
||||
let src_id = UbfU8::new(5);
|
||||
let dest_id = UbfU8::new(10);
|
||||
let transaction_seq_num = UbfU8::new(20);
|
||||
let mut pdu_conf = CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_seq_num)
|
||||
.expect("Generating common PDU config");
|
||||
let mut pdu_conf =
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_seq_num)
|
||||
.expect("Generating common PDU config");
|
||||
pdu_conf.crc_flag = crc_flag;
|
||||
pdu_conf.file_flag = fss;
|
||||
pdu_conf
|
||||
@ -647,7 +694,7 @@ mod tests {
|
||||
let src_id = UnsignedByteFieldU8::new(1);
|
||||
let dest_id = UnsignedByteFieldU8::new(2);
|
||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_id)
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||
.expect("common config creation failed");
|
||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
||||
assert_eq!(pdu_header.pdu_type(), PduType::FileDirective);
|
||||
@ -666,12 +713,43 @@ mod tests {
|
||||
assert_eq!(pdu_header.header_len(), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_basic_state_default() {
|
||||
let default_conf = CommonPduConfig::default();
|
||||
assert_eq!(default_conf.source_id(), UnsignedByteFieldU8::new(0).into());
|
||||
assert_eq!(default_conf.dest_id(), UnsignedByteFieldU8::new(0).into());
|
||||
assert_eq!(
|
||||
default_conf.transaction_seq_num,
|
||||
UnsignedByteFieldU8::new(0).into()
|
||||
);
|
||||
assert_eq!(default_conf.trans_mode, TransmissionMode::Acknowledged);
|
||||
assert_eq!(default_conf.direction, Direction::TowardsReceiver);
|
||||
assert_eq!(default_conf.crc_flag, CrcFlag::NoCrc);
|
||||
assert_eq!(default_conf.file_flag, LargeFileFlag::Normal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pdu_header_setter() {
|
||||
let src_id = UnsignedByteFieldU8::new(1);
|
||||
let dest_id = UnsignedByteFieldU8::new(2);
|
||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||
let mut common_pdu_cfg =
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||
.expect("common config creation failed");
|
||||
let other_src_id = UnsignedByteFieldU16::new(5);
|
||||
let other_dest_id = UnsignedByteFieldU16::new(6);
|
||||
let set_result = common_pdu_cfg.set_source_and_dest_id(other_src_id, other_dest_id);
|
||||
assert!(set_result.is_ok());
|
||||
assert_eq!(common_pdu_cfg.source_id(), other_src_id.into());
|
||||
assert_eq!(common_pdu_cfg.dest_id(), other_dest_id.into());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialization_1() {
|
||||
let src_id = UnsignedByteFieldU8::new(1);
|
||||
let dest_id = UnsignedByteFieldU8::new(2);
|
||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_id)
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||
.expect("common config creation failed");
|
||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
||||
let mut buf: [u8; 7] = [0; 7];
|
||||
@ -687,7 +765,7 @@ mod tests {
|
||||
let src_id = UnsignedByteFieldU8::new(1);
|
||||
let dest_id = UnsignedByteFieldU8::new(2);
|
||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_id)
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||
.expect("common config creation failed");
|
||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
||||
let mut buf: [u8; 7] = [0; 7];
|
||||
@ -706,7 +784,7 @@ mod tests {
|
||||
let dest_id = UnsignedByteFieldU16::new(0x0203);
|
||||
let transaction_id = UnsignedByteFieldU16::new(0x0405);
|
||||
let mut common_pdu_cfg =
|
||||
CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_id)
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||
.expect("common config creation failed");
|
||||
common_pdu_cfg.crc_flag = CrcFlag::WithCrc;
|
||||
common_pdu_cfg.direction = Direction::TowardsSender;
|
||||
@ -733,7 +811,7 @@ mod tests {
|
||||
let dest_id = UnsignedByteFieldU16::new(0x0203);
|
||||
let transaction_id = UnsignedByteFieldU16::new(0x0405);
|
||||
let mut common_pdu_cfg =
|
||||
CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_id)
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||
.expect("common config creation failed");
|
||||
common_pdu_cfg.crc_flag = CrcFlag::WithCrc;
|
||||
common_pdu_cfg.direction = Direction::TowardsSender;
|
||||
@ -760,7 +838,7 @@ mod tests {
|
||||
let src_id = UnsignedByteFieldU8::new(1);
|
||||
let dest_id = UnsignedByteFieldU8::new(2);
|
||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_id)
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||
.expect("common config creation failed");
|
||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
||||
let mut buf: [u8; 7] = [0; 7];
|
||||
@ -784,11 +862,13 @@ mod tests {
|
||||
let res = PduHeader::from_bytes(&buf);
|
||||
assert!(res.is_err());
|
||||
let error = res.unwrap_err();
|
||||
if let PduError::ByteConversionError(ByteConversionError::FromSliceTooSmall(missmatch)) =
|
||||
error
|
||||
if let PduError::ByteConversionError(ByteConversionError::FromSliceTooSmall {
|
||||
found,
|
||||
expected,
|
||||
}) = error
|
||||
{
|
||||
assert_eq!(missmatch.found, 3);
|
||||
assert_eq!(missmatch.expected, FIXED_HEADER_LEN);
|
||||
assert_eq!(found, 3);
|
||||
assert_eq!(expected, FIXED_HEADER_LEN);
|
||||
} else {
|
||||
panic!("invalid exception: {}", error);
|
||||
}
|
||||
@ -799,7 +879,7 @@ mod tests {
|
||||
let src_id = UnsignedByteFieldU8::new(1);
|
||||
let dest_id = UnsignedByteFieldU8::new(2);
|
||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_id)
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||
.expect("common config creation failed");
|
||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
||||
let mut buf: [u8; 7] = [0; 7];
|
||||
@ -808,11 +888,13 @@ mod tests {
|
||||
let header = PduHeader::from_bytes(&buf[0..6]);
|
||||
assert!(header.is_err());
|
||||
let error = header.unwrap_err();
|
||||
if let PduError::ByteConversionError(ByteConversionError::FromSliceTooSmall(missmatch)) =
|
||||
error
|
||||
if let PduError::ByteConversionError(ByteConversionError::FromSliceTooSmall {
|
||||
found,
|
||||
expected,
|
||||
}) = error
|
||||
{
|
||||
assert_eq!(missmatch.found, 6);
|
||||
assert_eq!(missmatch.expected, 7);
|
||||
assert_eq!(found, 6);
|
||||
assert_eq!(expected, 7);
|
||||
}
|
||||
}
|
||||
|
||||
@ -822,7 +904,8 @@ mod tests {
|
||||
let dest_id = UbfU8::new(2);
|
||||
let transaction_seq_id = UbfU8::new(3);
|
||||
let invalid_byte_field = UnsignedByteField::new(3, 5);
|
||||
let pdu_conf_res = CommonPduConfig::new_with_defaults(src_id, dest_id, invalid_byte_field);
|
||||
let pdu_conf_res =
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, invalid_byte_field);
|
||||
assert!(pdu_conf_res.is_err());
|
||||
let error = pdu_conf_res.unwrap_err();
|
||||
if let PduError::InvalidTransactionSeqNumLen(len) = error {
|
||||
@ -830,7 +913,7 @@ mod tests {
|
||||
} else {
|
||||
panic!("Invalid exception: {}", error)
|
||||
}
|
||||
let pdu_conf_res = CommonPduConfig::new_with_defaults(
|
||||
let pdu_conf_res = CommonPduConfig::new_with_byte_fields(
|
||||
invalid_byte_field,
|
||||
invalid_byte_field,
|
||||
transaction_seq_id,
|
||||
@ -848,12 +931,17 @@ mod tests {
|
||||
let src_id = UnsignedByteField::new(1, 5);
|
||||
let dest_id = UnsignedByteField::new(2, 5);
|
||||
let transaction_seq_id = UbfU8::new(3);
|
||||
let pdu_conf_res = CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_seq_id);
|
||||
let pdu_conf_res =
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_seq_id);
|
||||
assert!(pdu_conf_res.is_err());
|
||||
let error = pdu_conf_res.unwrap_err();
|
||||
if let PduError::SourceDestIdLenMissmatch((src_len, dest_len)) = error {
|
||||
assert_eq!(src_len, 1);
|
||||
assert_eq!(dest_len, 2);
|
||||
if let PduError::SourceDestIdLenMissmatch {
|
||||
src_id_len,
|
||||
dest_id_len,
|
||||
} = error
|
||||
{
|
||||
assert_eq!(src_id_len, 1);
|
||||
assert_eq!(dest_id_len, 2);
|
||||
}
|
||||
}
|
||||
|
||||
@ -862,7 +950,7 @@ mod tests {
|
||||
let src_id = UnsignedByteFieldU8::new(1);
|
||||
let dest_id = UnsignedByteFieldU8::new(2);
|
||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_id)
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||
.expect("common config creation failed");
|
||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
||||
let mut buf: [u8; 7] = [0; 7];
|
||||
@ -886,7 +974,7 @@ mod tests {
|
||||
let src_id = UnsignedByteFieldU8::new(1);
|
||||
let dest_id = UnsignedByteFieldU8::new(2);
|
||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_defaults(src_id, dest_id, transaction_id)
|
||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||
.expect("common config creation failed");
|
||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
||||
let mut buf: [u8; 7] = [0; 7];
|
||||
|
@ -4,11 +4,13 @@ use crate::cfdp::lv::{
|
||||
};
|
||||
use crate::cfdp::TlvLvError;
|
||||
use crate::util::{UnsignedByteField, UnsignedByteFieldError, UnsignedEnum};
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub mod msg_to_user;
|
||||
|
||||
pub const MIN_TLV_LEN: usize = 2;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
@ -70,6 +72,9 @@ impl From<TlvTypeField> for u8 {
|
||||
|
||||
/// Generic CFDP type-length-value (TLV) abstraction as specified in CFDP 5.1.9.
|
||||
///
|
||||
/// Please note that this class is zero-copy and does not generate a copy of the value data for
|
||||
/// both the regular [Self::new] constructor and the [Self::from_bytes] constructor.
|
||||
///
|
||||
/// # Lifetimes
|
||||
/// * `data`: If the TLV is generated from a raw bytestream, this will be the lifetime of
|
||||
/// the raw bytestream. If the TLV is generated from a raw slice or a similar data reference,
|
||||
@ -98,22 +103,41 @@ impl<'data> Tlv<'data> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks whether the type field contains one of the standard types specified in the CFDP
|
||||
/// standard and is part of the [TlvType] enum.
|
||||
pub fn is_standard_tlv(&self) -> bool {
|
||||
if let TlvTypeField::Standard(_) = self.tlv_type_field {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Returns the standard TLV type if the TLV field is not a custom field
|
||||
pub fn tlv_type(&self) -> Option<TlvType> {
|
||||
if let TlvTypeField::Standard(tlv_type) = self.tlv_type_field {
|
||||
Some(tlv_type)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tlv_type_field(&self) -> TlvTypeField {
|
||||
self.tlv_type_field
|
||||
}
|
||||
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
generic_len_check_data_serialization(buf, self.len_value(), MIN_TLV_LEN)?;
|
||||
generic_len_check_data_serialization(buf, self.value().len(), MIN_TLV_LEN)?;
|
||||
buf[0] = self.tlv_type_field.into();
|
||||
self.lv.write_to_be_bytes_no_len_check(&mut buf[1..]);
|
||||
Ok(self.len_full())
|
||||
}
|
||||
|
||||
pub fn value(&self) -> Option<&[u8]> {
|
||||
pub fn value(&self) -> &[u8] {
|
||||
self.lv.value()
|
||||
}
|
||||
|
||||
/// Returns the length of the value part, not including the length byte.
|
||||
/// Helper method to retrieve the length of the value. Simply calls the [slice::len] method of
|
||||
/// [Self::value]
|
||||
pub fn len_value(&self) -> usize {
|
||||
self.lv.len_value()
|
||||
}
|
||||
@ -134,10 +158,20 @@ impl<'data> Tlv<'data> {
|
||||
/// [Self::len_full].
|
||||
pub fn from_bytes(buf: &'data [u8]) -> Result<Tlv<'data>, TlvLvError> {
|
||||
generic_len_check_deserialization(buf, MIN_TLV_LEN)?;
|
||||
Ok(Self {
|
||||
let mut tlv = Self {
|
||||
tlv_type_field: TlvTypeField::from(buf[0]),
|
||||
lv: Lv::from_bytes(&buf[MIN_LV_LEN..])?,
|
||||
})
|
||||
};
|
||||
// We re-use this field so we do not need an additional struct field to store the raw start
|
||||
// of the TLV.
|
||||
tlv.lv.raw_data = Some(buf);
|
||||
Ok(tlv)
|
||||
}
|
||||
|
||||
/// If the TLV was generated from a raw bytestream using [Self::from_bytes], the raw start
|
||||
/// of the TLV can be retrieved with this method.
|
||||
pub fn raw_data(&self) -> Option<&[u8]> {
|
||||
self.lv.raw_data()
|
||||
}
|
||||
}
|
||||
|
||||
@ -166,10 +200,10 @@ impl EntityIdTlv {
|
||||
|
||||
fn len_check(buf: &[u8]) -> Result<(), ByteConversionError> {
|
||||
if buf.len() < 2 {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: 2,
|
||||
}));
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -234,21 +268,19 @@ impl<'data> TryFrom<Tlv<'data>> for EntityIdTlv {
|
||||
)));
|
||||
}
|
||||
}
|
||||
if value.len_value() != 1
|
||||
&& value.len_value() != 2
|
||||
&& value.len_value() != 4
|
||||
&& value.len_value() != 8
|
||||
{
|
||||
return Err(TlvLvError::InvalidValueLength(value.len_value()));
|
||||
let len_value = value.value().len();
|
||||
if len_value != 1 && len_value != 2 && len_value != 4 && len_value != 8 {
|
||||
return Err(TlvLvError::InvalidValueLength(len_value));
|
||||
}
|
||||
Ok(Self::new(
|
||||
UnsignedByteField::new_from_be_bytes(value.len_value(), value.value().unwrap())
|
||||
.map_err(|e| match e {
|
||||
UnsignedByteField::new_from_be_bytes(len_value, value.value()).map_err(
|
||||
|e| match e {
|
||||
UnsignedByteFieldError::ByteConversionError(e) => e,
|
||||
// This can not happen, we checked for the length validity, and the data is always smaller than
|
||||
// 255 bytes.
|
||||
_ => panic!("unexpected error"),
|
||||
})?,
|
||||
},
|
||||
)?,
|
||||
))
|
||||
}
|
||||
}
|
||||
@ -390,10 +422,10 @@ impl<'first_name, 'second_name> FilestoreRequestTlv<'first_name, 'second_name> {
|
||||
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
if buf.len() < self.len_full() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: self.len_full(),
|
||||
}));
|
||||
});
|
||||
}
|
||||
buf[0] = TlvType::FilestoreRequest as u8;
|
||||
buf[1] = self.len_value() as u8;
|
||||
@ -417,10 +449,10 @@ impl<'first_name, 'second_name> FilestoreRequestTlv<'first_name, 'second_name> {
|
||||
buf: &'longest [u8],
|
||||
) -> Result<Self, TlvLvError> {
|
||||
if buf.len() < 2 {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: 2,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
verify_tlv_type(buf[0], TlvType::FilestoreRequest)?;
|
||||
@ -454,8 +486,8 @@ mod tests {
|
||||
use crate::cfdp::TlvLvError;
|
||||
use crate::util::{UbfU8, UnsignedEnum};
|
||||
|
||||
const TLV_TEST_STR_0: &'static str = "hello.txt";
|
||||
const TLV_TEST_STR_1: &'static str = "hello2.txt";
|
||||
const TLV_TEST_STR_0: &str = "hello.txt";
|
||||
const TLV_TEST_STR_1: &str = "hello2.txt";
|
||||
|
||||
#[test]
|
||||
fn test_basic() {
|
||||
@ -470,10 +502,10 @@ mod tests {
|
||||
TlvTypeField::Standard(TlvType::EntityId)
|
||||
);
|
||||
assert_eq!(tlv_res.len_full(), 3);
|
||||
assert_eq!(tlv_res.value().len(), 1);
|
||||
assert_eq!(tlv_res.len_value(), 1);
|
||||
assert!(!tlv_res.is_empty());
|
||||
assert!(tlv_res.value().is_some());
|
||||
assert_eq!(tlv_res.value().unwrap()[0], 5);
|
||||
assert_eq!(tlv_res.value()[0], 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -498,26 +530,27 @@ mod tests {
|
||||
assert!(entity_id.write_to_be_bytes(&mut buf[2..]).is_ok());
|
||||
buf[0] = TlvType::EntityId as u8;
|
||||
buf[1] = 1;
|
||||
let tlv_from_raw = Tlv::from_bytes(&mut buf);
|
||||
let tlv_from_raw = Tlv::from_bytes(&buf);
|
||||
assert!(tlv_from_raw.is_ok());
|
||||
let tlv_from_raw = tlv_from_raw.unwrap();
|
||||
assert!(tlv_from_raw.raw_data().is_some());
|
||||
assert_eq!(tlv_from_raw.raw_data().unwrap(), buf);
|
||||
assert_eq!(
|
||||
tlv_from_raw.tlv_type_field(),
|
||||
TlvTypeField::Standard(TlvType::EntityId)
|
||||
);
|
||||
assert_eq!(tlv_from_raw.len_value(), 1);
|
||||
assert_eq!(tlv_from_raw.value().len(), 1);
|
||||
assert_eq!(tlv_from_raw.len_full(), 3);
|
||||
assert!(tlv_from_raw.value().is_some());
|
||||
assert_eq!(tlv_from_raw.value().unwrap()[0], 5);
|
||||
assert_eq!(tlv_from_raw.value()[0], 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty() {
|
||||
let tlv_empty = Tlv::new_empty(TlvType::MsgToUser);
|
||||
assert!(tlv_empty.value().is_none());
|
||||
assert_eq!(tlv_empty.value().len(), 0);
|
||||
assert!(tlv_empty.is_empty());
|
||||
assert_eq!(tlv_empty.len_full(), 2);
|
||||
assert_eq!(tlv_empty.len_value(), 0);
|
||||
assert!(tlv_empty.value().is_empty());
|
||||
assert_eq!(
|
||||
tlv_empty.tlv_type_field(),
|
||||
TlvTypeField::Standard(TlvType::MsgToUser)
|
||||
@ -538,17 +571,17 @@ mod tests {
|
||||
let mut buf: [u8; 4] = [0; 4];
|
||||
buf[0] = TlvType::MsgToUser as u8;
|
||||
buf[1] = 0;
|
||||
let tlv_empty = Tlv::from_bytes(&mut buf);
|
||||
let tlv_empty = Tlv::from_bytes(&buf);
|
||||
assert!(tlv_empty.is_ok());
|
||||
let tlv_empty = tlv_empty.unwrap();
|
||||
assert!(tlv_empty.is_empty());
|
||||
assert!(tlv_empty.value().is_none());
|
||||
assert_eq!(tlv_empty.value().len(), 0);
|
||||
assert_eq!(
|
||||
tlv_empty.tlv_type_field(),
|
||||
TlvTypeField::Standard(TlvType::MsgToUser)
|
||||
);
|
||||
assert_eq!(tlv_empty.len_full(), 2);
|
||||
assert_eq!(tlv_empty.len_value(), 0);
|
||||
assert!(tlv_empty.value().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -570,11 +603,11 @@ mod tests {
|
||||
buf[0] = 3;
|
||||
buf[1] = 1;
|
||||
buf[2] = 5;
|
||||
let tlv = Tlv::from_bytes(&mut buf);
|
||||
let tlv = Tlv::from_bytes(&buf);
|
||||
assert!(tlv.is_ok());
|
||||
let tlv = tlv.unwrap();
|
||||
assert_eq!(tlv.tlv_type_field(), TlvTypeField::Custom(3));
|
||||
assert_eq!(tlv.len_value(), 1);
|
||||
assert_eq!(tlv.value().len(), 1);
|
||||
assert_eq!(tlv.len_full(), 3);
|
||||
}
|
||||
|
110
src/cfdp/tlv/msg_to_user.rs
Normal file
110
src/cfdp/tlv/msg_to_user.rs
Normal file
@ -0,0 +1,110 @@
|
||||
//! Abstractions for the Message to User CFDP TLV subtype.
|
||||
use super::{Tlv, TlvLvError, TlvType, TlvTypeField};
|
||||
use crate::ByteConversionError;
|
||||
use delegate::delegate;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub struct MsgToUserTlv<'data> {
|
||||
pub tlv: Tlv<'data>,
|
||||
}
|
||||
|
||||
impl<'data> MsgToUserTlv<'data> {
|
||||
/// Create a new message to user TLV where the type field is set correctly.
|
||||
pub fn new(value: &'data [u8]) -> Result<MsgToUserTlv<'data>, TlvLvError> {
|
||||
Ok(Self {
|
||||
tlv: Tlv::new(TlvType::MsgToUser, value)?,
|
||||
})
|
||||
}
|
||||
|
||||
delegate! {
|
||||
to self.tlv {
|
||||
pub fn tlv_type_field(&self) -> TlvTypeField;
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;
|
||||
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;
|
||||
/// Returns the full raw length, including the length byte.
|
||||
pub fn len_full(&self) -> usize;
|
||||
/// Checks whether the value field is empty.
|
||||
pub fn is_empty(&self) -> bool;
|
||||
/// If the TLV was generated from a raw bytestream using [Self::from_bytes], the raw start
|
||||
/// of the TLV can be retrieved with this method.
|
||||
pub fn raw_data(&self) -> Option<&[u8]>;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_standard_tlv(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub fn tlv_type(&self) -> Option<TlvType> {
|
||||
Some(TlvType::MsgToUser)
|
||||
}
|
||||
|
||||
/// Check whether this message is a reserved CFDP message like a Proxy Operation Message.
|
||||
pub fn is_reserved_cfdp_msg(&self) -> bool {
|
||||
if self.value().len() < 4 {
|
||||
return false;
|
||||
}
|
||||
let value = self.value();
|
||||
if value[0] == b'c' && value[1] == b'f' && value[2] == b'd' && value[3] == b'p' {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// This is a thin wrapper around [Tlv::from_bytes] with the additional type check.
|
||||
pub fn from_bytes(buf: &'data [u8]) -> Result<MsgToUserTlv<'data>, TlvLvError> {
|
||||
let msg_to_user = Self {
|
||||
tlv: Tlv::from_bytes(buf)?,
|
||||
};
|
||||
match msg_to_user.tlv_type_field() {
|
||||
TlvTypeField::Standard(tlv_type) => {
|
||||
if tlv_type != TlvType::MsgToUser {
|
||||
return Err(TlvLvError::InvalidTlvTypeField((
|
||||
tlv_type as u8,
|
||||
Some(TlvType::MsgToUser as u8),
|
||||
)));
|
||||
}
|
||||
}
|
||||
TlvTypeField::Custom(raw) => {
|
||||
return Err(TlvLvError::InvalidTlvTypeField((
|
||||
raw,
|
||||
Some(TlvType::MsgToUser as u8),
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(msg_to_user)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn test_basic() {
|
||||
let custom_value: [u8; 4] = [1, 2, 3, 4];
|
||||
let msg_to_user = MsgToUserTlv::new(&custom_value);
|
||||
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.value(), custom_value);
|
||||
assert_eq!(msg_to_user.value().len(), 4);
|
||||
assert_eq!(msg_to_user.len_value(), 4);
|
||||
assert_eq!(msg_to_user.len_full(), 6);
|
||||
assert!(!msg_to_user.is_empty());
|
||||
assert!(msg_to_user.raw_data().is_none());
|
||||
assert!(!msg_to_user.is_reserved_cfdp_msg());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reserved_msg() {
|
||||
let reserved_str = "cfdp";
|
||||
let msg_to_user = MsgToUserTlv::new(reserved_str.as_bytes());
|
||||
assert!(msg_to_user.is_ok());
|
||||
let msg_to_user = msg_to_user.unwrap();
|
||||
assert!(msg_to_user.is_reserved_cfdp_msg());
|
||||
}
|
||||
}
|
@ -1,8 +1,8 @@
|
||||
//! Common definitions and helpers required to create PUS TMTC packets according to
|
||||
//! [ECSS-E-ST-70-41C](https://ecss.nl/standard/ecss-e-st-70-41c-space-engineering-telemetry-and-telecommand-packet-utilization-15-april-2016/)
|
||||
//!
|
||||
//! You can find the PUS telecommand definitions in the [crate::tc] module and ithe PUS telemetry definitions
|
||||
//! inside the [crate::tm] module.
|
||||
//! You can find the PUS telecommand definitions in the [tc] module and ithe PUS telemetry definitions
|
||||
//! inside the [tm] module.
|
||||
use crate::{ByteConversionError, CcsdsPacket, CRC_CCITT_FALSE};
|
||||
use core::fmt::{Debug, Display, Formatter};
|
||||
use core::mem::size_of;
|
||||
@ -15,6 +15,8 @@ use std::error::Error;
|
||||
pub mod event;
|
||||
pub mod hk;
|
||||
pub mod scheduling;
|
||||
pub mod tc;
|
||||
pub mod tm;
|
||||
pub mod verification;
|
||||
|
||||
pub type CrcType = u16;
|
||||
@ -149,7 +151,7 @@ pub enum PusError {
|
||||
NoRawData,
|
||||
/// CRC16 needs to be calculated first
|
||||
CrcCalculationMissing,
|
||||
ByteConversionError(ByteConversionError),
|
||||
ByteConversion(ByteConversionError),
|
||||
}
|
||||
|
||||
impl Display for PusError {
|
||||
@ -173,7 +175,7 @@ impl Display for PusError {
|
||||
PusError::CrcCalculationMissing => {
|
||||
write!(f, "crc16 was not calculated")
|
||||
}
|
||||
PusError::ByteConversionError(e) => {
|
||||
PusError::ByteConversion(e) => {
|
||||
write!(f, "low level byte conversion error: {e}")
|
||||
}
|
||||
}
|
||||
@ -183,7 +185,7 @@ impl Display for PusError {
|
||||
#[cfg(feature = "std")]
|
||||
impl Error for PusError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
if let PusError::ByteConversionError(e) = self {
|
||||
if let PusError::ByteConversion(e) = self {
|
||||
return Some(e);
|
||||
}
|
||||
None
|
||||
@ -192,7 +194,7 @@ impl Error for PusError {
|
||||
|
||||
impl From<ByteConversionError> for PusError {
|
||||
fn from(e: ByteConversionError) -> Self {
|
||||
PusError::ByteConversionError(e)
|
||||
PusError::ByteConversion(e)
|
||||
}
|
||||
}
|
||||
|
||||
@ -204,8 +206,7 @@ pub trait PusPacket: CcsdsPacket {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
|
||||
fn user_data(&self) -> Option<&[u8]>;
|
||||
fn user_data(&self) -> &[u8];
|
||||
fn crc16(&self) -> Option<u16>;
|
||||
}
|
||||
|
||||
@ -249,11 +250,10 @@ pub(crate) fn user_data_from_raw(
|
||||
total_len: usize,
|
||||
raw_data_len: usize,
|
||||
slice: &[u8],
|
||||
) -> Result<Option<&[u8]>, PusError> {
|
||||
) -> Result<&[u8], PusError> {
|
||||
match current_idx {
|
||||
_ if current_idx == total_len - 2 => Ok(None),
|
||||
_ if current_idx > total_len - 2 => Err(PusError::RawDataTooShort(raw_data_len)),
|
||||
_ => Ok(Some(&slice[current_idx..total_len - 2])),
|
||||
_ => Ok(&slice[current_idx..total_len - 2]),
|
||||
}
|
||||
}
|
||||
|
||||
@ -397,9 +397,9 @@ mod tests {
|
||||
assert!(res.is_err());
|
||||
let error = res.unwrap_err();
|
||||
match error {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.expected, 2);
|
||||
assert_eq!(missmatch.found, 1);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(expected, 2);
|
||||
assert_eq!(found, 1);
|
||||
}
|
||||
_ => {
|
||||
panic!("Unexpected error {:?}", error);
|
||||
@ -428,9 +428,9 @@ mod tests {
|
||||
assert!(res.is_err());
|
||||
let error = res.unwrap_err();
|
||||
match error {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.expected, 4);
|
||||
assert_eq!(missmatch.found, 3);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(expected, 4);
|
||||
assert_eq!(found, 3);
|
||||
}
|
||||
_ => {
|
||||
panic!("Unexpected error {:?}", error);
|
||||
|
@ -5,13 +5,13 @@
|
||||
//!
|
||||
//! ```rust
|
||||
//! use spacepackets::{CcsdsPacket, SpHeader};
|
||||
//! use spacepackets::tc::{PusTc, PusTcSecondaryHeader};
|
||||
//! use spacepackets::ecss::{PusPacket, SerializablePusPacket};
|
||||
//! use spacepackets::ecss::tc::{PusTcCreator, PusTcReader, PusTcSecondaryHeader};
|
||||
//!
|
||||
//! // Create a ping telecommand with no user application data
|
||||
//! let mut sph = SpHeader::tc_unseg(0x02, 0x34, 0).unwrap();
|
||||
//! let tc_header = PusTcSecondaryHeader::new_simple(17, 1);
|
||||
//! let pus_tc = PusTc::new(&mut sph, tc_header, None, true);
|
||||
//! let pus_tc = PusTcCreator::new(&mut sph, tc_header, None, true);
|
||||
//! println!("{:?}", pus_tc);
|
||||
//! assert_eq!(pus_tc.service(), 17);
|
||||
//! assert_eq!(pus_tc.subservice(), 1);
|
||||
@ -26,19 +26,17 @@
|
||||
//! println!("{:?}", &test_buf[0..size]);
|
||||
//!
|
||||
//! // Deserialize from the raw byte representation
|
||||
//! let pus_tc_deserialized = PusTc::from_bytes(&test_buf).expect("Deserialization failed");
|
||||
//! 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.apid(), 0x02);
|
||||
//! ```
|
||||
use crate::ecss::{
|
||||
ccsds_impl, crc_from_raw_data, crc_procedure, sp_header_impls, user_data_from_raw,
|
||||
ccsds_impl, crc_from_raw_data, sp_header_impls, user_data_from_raw,
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error, CrcType, PusError, PusPacket, PusVersion,
|
||||
SerializablePusPacket,
|
||||
};
|
||||
use crate::{
|
||||
ByteConversionError, CcsdsPacket, PacketType, SequenceFlags, SizeMissmatch, CCSDS_HEADER_LEN,
|
||||
};
|
||||
use crate::{ByteConversionError, CcsdsPacket, PacketType, SequenceFlags, CCSDS_HEADER_LEN};
|
||||
use crate::{SpHeader, CRC_CCITT_FALSE};
|
||||
use core::mem::size_of;
|
||||
use delegate::delegate;
|
||||
@ -49,12 +47,17 @@ use zerocopy::AsBytes;
|
||||
#[cfg(feature = "alloc")]
|
||||
use alloc::vec::Vec;
|
||||
|
||||
pub use legacy_tc::*;
|
||||
|
||||
/// PUS C secondary header length is fixed
|
||||
pub const PUC_TC_SECONDARY_HEADER_LEN: usize = size_of::<zc::PusTcSecondaryHeader>();
|
||||
pub const PUS_TC_MIN_LEN_WITHOUT_APP_DATA: usize =
|
||||
CCSDS_HEADER_LEN + PUC_TC_SECONDARY_HEADER_LEN + size_of::<CrcType>();
|
||||
const PUS_VERSION: PusVersion = PusVersion::PusC;
|
||||
|
||||
/// Marker trait for PUS telecommand structures.
|
||||
pub trait IsPusTelecommand {}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Debug)]
|
||||
enum AckOpts {
|
||||
Acceptance = 0b1000,
|
||||
@ -77,11 +80,11 @@ pub trait GenericPusTcSecondaryHeader {
|
||||
}
|
||||
|
||||
pub mod zc {
|
||||
use crate::ecss::tc::GenericPusTcSecondaryHeader;
|
||||
use crate::ecss::{PusError, PusVersion};
|
||||
use crate::tc::GenericPusTcSecondaryHeader;
|
||||
use zerocopy::{AsBytes, FromBytes, NetworkEndian, Unaligned, U16};
|
||||
use zerocopy::{AsBytes, FromBytes, FromZeroes, NetworkEndian, Unaligned, U16};
|
||||
|
||||
#[derive(FromBytes, AsBytes, Unaligned)]
|
||||
#[derive(FromZeroes, FromBytes, AsBytes, Unaligned)]
|
||||
#[repr(C)]
|
||||
pub struct PusTcSecondaryHeader {
|
||||
version_ack: u8,
|
||||
@ -90,9 +93,9 @@ pub mod zc {
|
||||
source_id: U16<NetworkEndian>,
|
||||
}
|
||||
|
||||
impl TryFrom<crate::tc::PusTcSecondaryHeader> for PusTcSecondaryHeader {
|
||||
impl TryFrom<crate::ecss::tc::PusTcSecondaryHeader> for PusTcSecondaryHeader {
|
||||
type Error = PusError;
|
||||
fn try_from(value: crate::tc::PusTcSecondaryHeader) -> Result<Self, Self::Error> {
|
||||
fn try_from(value: crate::ecss::tc::PusTcSecondaryHeader) -> Result<Self, Self::Error> {
|
||||
if value.version != PusVersion::PusC {
|
||||
return Err(PusError::VersionNotSupported(value.version));
|
||||
}
|
||||
@ -206,35 +209,342 @@ impl PusTcSecondaryHeader {
|
||||
}
|
||||
}
|
||||
|
||||
/// This class models the PUS C telecommand packet. It is the primary data structure to generate the
|
||||
/// raw byte representation of a PUS telecommand or to deserialize from one from raw bytes.
|
||||
pub mod legacy_tc {
|
||||
use crate::ecss::tc::{
|
||||
zc, GenericPusTcSecondaryHeader, IsPusTelecommand, PusTcSecondaryHeader, ACK_ALL,
|
||||
PUC_TC_SECONDARY_HEADER_LEN, PUS_TC_MIN_LEN_WITHOUT_APP_DATA,
|
||||
};
|
||||
use crate::ecss::{
|
||||
ccsds_impl, crc_from_raw_data, crc_procedure, sp_header_impls,
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error, PusError, PusPacket, SerializablePusPacket,
|
||||
CCSDS_HEADER_LEN,
|
||||
};
|
||||
use crate::ecss::{user_data_from_raw, PusVersion};
|
||||
use crate::SequenceFlags;
|
||||
use crate::{ByteConversionError, CcsdsPacket, PacketType, SpHeader, CRC_CCITT_FALSE};
|
||||
use core::mem::size_of;
|
||||
use delegate::delegate;
|
||||
use zerocopy::AsBytes;
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
use alloc::vec::Vec;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// This class models the PUS C telecommand packet. It is the primary data structure to generate the
|
||||
/// raw byte representation of a PUS telecommand or to deserialize from one from raw bytes.
|
||||
///
|
||||
/// This class also derives the [serde::Serialize] and [serde::Deserialize] trait if the
|
||||
/// [serde] feature is used, which allows to send around TC packets in a raw byte format using a
|
||||
/// serde provider like [postcard](https://docs.rs/postcard/latest/postcard/).
|
||||
///
|
||||
/// There is no spare bytes support yet.
|
||||
///
|
||||
/// # Lifetimes
|
||||
///
|
||||
/// * `'raw_data` - If the TC is not constructed from a raw slice, this will be the life time of
|
||||
/// a buffer where the user provided application data will be serialized into. If it
|
||||
/// is, this is the lifetime of the raw byte slice it is constructed from.
|
||||
#[derive(Eq, Copy, Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct PusTc<'raw_data> {
|
||||
sp_header: SpHeader,
|
||||
pub sec_header: PusTcSecondaryHeader,
|
||||
/// If this is set to false, a manual call to [PusTc::calc_own_crc16] or
|
||||
/// [PusTc::update_packet_fields] is necessary for the serialized or cached CRC16 to be valid.
|
||||
pub calc_crc_on_serialization: bool,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
raw_data: Option<&'raw_data [u8]>,
|
||||
app_data: &'raw_data [u8],
|
||||
crc16: Option<u16>,
|
||||
}
|
||||
|
||||
impl<'raw_data> PusTc<'raw_data> {
|
||||
/// Generates a new struct instance.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `sp_header` - Space packet header information. The correct packet type will be set
|
||||
/// automatically
|
||||
/// * `sec_header` - Information contained in the data field header, including the service
|
||||
/// and subservice type
|
||||
/// * `app_data` - Custom application data
|
||||
/// * `set_ccsds_len` - Can be used to automatically update the CCSDS space packet data length
|
||||
/// field. If this is not set to true, [PusTc::update_ccsds_data_len] can be called to set
|
||||
/// the correct value to this field manually
|
||||
#[deprecated(
|
||||
since = "0.7.0",
|
||||
note = "Use specialized PusTcCreator or PusTcReader classes instead"
|
||||
)]
|
||||
pub fn new(
|
||||
sp_header: &mut SpHeader,
|
||||
sec_header: PusTcSecondaryHeader,
|
||||
app_data: Option<&'raw_data [u8]>,
|
||||
set_ccsds_len: bool,
|
||||
) -> Self {
|
||||
sp_header.set_packet_type(PacketType::Tc);
|
||||
sp_header.set_sec_header_flag();
|
||||
let mut pus_tc = Self {
|
||||
sp_header: *sp_header,
|
||||
raw_data: None,
|
||||
app_data: app_data.unwrap_or(&[]),
|
||||
sec_header,
|
||||
calc_crc_on_serialization: true,
|
||||
crc16: None,
|
||||
};
|
||||
if set_ccsds_len {
|
||||
pus_tc.update_ccsds_data_len();
|
||||
}
|
||||
pus_tc
|
||||
}
|
||||
|
||||
/// Simplified version of the [PusTc::new] function which allows to only specify service and
|
||||
/// subservice instead of the full PUS TC secondary header.
|
||||
#[deprecated(
|
||||
since = "0.7.0",
|
||||
note = "Use specialized PusTcCreator or PusTcReader classes instead"
|
||||
)]
|
||||
pub fn new_simple(
|
||||
sph: &mut SpHeader,
|
||||
service: u8,
|
||||
subservice: u8,
|
||||
app_data: Option<&'raw_data [u8]>,
|
||||
set_ccsds_len: bool,
|
||||
) -> Self {
|
||||
#[allow(deprecated)]
|
||||
Self::new(
|
||||
sph,
|
||||
PusTcSecondaryHeader::new(service, subservice, ACK_ALL, 0),
|
||||
app_data,
|
||||
set_ccsds_len,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn sp_header(&self) -> &SpHeader {
|
||||
&self.sp_header
|
||||
}
|
||||
|
||||
pub fn set_ack_field(&mut self, ack: u8) -> bool {
|
||||
if ack > 0b1111 {
|
||||
return false;
|
||||
}
|
||||
self.sec_header.ack = ack & 0b1111;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn set_source_id(&mut self, source_id: u16) {
|
||||
self.sec_header.source_id = source_id;
|
||||
}
|
||||
|
||||
sp_header_impls!();
|
||||
|
||||
/// Calculate the CCSDS space packet data length field and sets it
|
||||
/// This is called automatically if the `set_ccsds_len` argument in the [PusTc::new] call was
|
||||
/// used.
|
||||
/// If this was not done or the application data is set or changed after construction,
|
||||
/// this function needs to be called to ensure that the data length field of the CCSDS header
|
||||
/// is set correctly.
|
||||
pub fn update_ccsds_data_len(&mut self) {
|
||||
self.sp_header.data_len =
|
||||
self.len_packed() as u16 - size_of::<crate::zc::SpHeader>() as u16 - 1;
|
||||
}
|
||||
|
||||
/// This function should be called before the TC packet is serialized if
|
||||
/// [PusTc::calc_crc_on_serialization] is set to False. It will calculate and cache the CRC16.
|
||||
pub fn calc_own_crc16(&mut self) {
|
||||
let mut digest = CRC_CCITT_FALSE.digest();
|
||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||
digest.update(sph_zc.as_bytes());
|
||||
let pus_tc_header = zc::PusTcSecondaryHeader::try_from(self.sec_header).unwrap();
|
||||
digest.update(pus_tc_header.as_bytes());
|
||||
if !self.app_data.is_empty() {
|
||||
digest.update(self.app_data);
|
||||
}
|
||||
self.crc16 = Some(digest.finalize())
|
||||
}
|
||||
|
||||
/// This helper function calls both [PusTc::update_ccsds_data_len] and [PusTc::calc_own_crc16].
|
||||
pub fn update_packet_fields(&mut self) {
|
||||
self.update_ccsds_data_len();
|
||||
self.calc_own_crc16();
|
||||
}
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
||||
pub fn append_to_vec(&self, vec: &mut Vec<u8>) -> Result<usize, PusError> {
|
||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||
let appended_len = PUS_TC_MIN_LEN_WITHOUT_APP_DATA + self.app_data.len();
|
||||
let start_idx = vec.len();
|
||||
let mut ser_len = 0;
|
||||
vec.extend_from_slice(sph_zc.as_bytes());
|
||||
ser_len += sph_zc.as_bytes().len();
|
||||
// The PUS version is hardcoded to PUS C
|
||||
let pus_tc_header = zc::PusTcSecondaryHeader::try_from(self.sec_header).unwrap();
|
||||
vec.extend_from_slice(pus_tc_header.as_bytes());
|
||||
ser_len += pus_tc_header.as_bytes().len();
|
||||
vec.extend_from_slice(self.app_data);
|
||||
ser_len += self.app_data.len();
|
||||
let crc16 = crc_procedure(
|
||||
self.calc_crc_on_serialization,
|
||||
&self.crc16,
|
||||
start_idx,
|
||||
ser_len,
|
||||
&vec[start_idx..ser_len],
|
||||
)?;
|
||||
vec.extend_from_slice(crc16.to_be_bytes().as_slice());
|
||||
Ok(appended_len)
|
||||
}
|
||||
|
||||
/// Create a [PusTc] instance from a raw slice. On success, it returns a tuple containing
|
||||
/// the instance and the found byte length of the packet.
|
||||
#[deprecated(
|
||||
since = "0.7.0",
|
||||
note = "Use specialized PusTcCreator or PusTcReader classes instead"
|
||||
)]
|
||||
pub fn from_bytes(slice: &'raw_data [u8]) -> Result<(Self, usize), PusError> {
|
||||
let raw_data_len = slice.len();
|
||||
if raw_data_len < PUS_TC_MIN_LEN_WITHOUT_APP_DATA {
|
||||
return Err(PusError::RawDataTooShort(raw_data_len));
|
||||
}
|
||||
let mut current_idx = 0;
|
||||
let (sp_header, _) = SpHeader::from_be_bytes(&slice[0..CCSDS_HEADER_LEN])?;
|
||||
current_idx += CCSDS_HEADER_LEN;
|
||||
let total_len = sp_header.total_len();
|
||||
if raw_data_len < total_len || total_len < PUS_TC_MIN_LEN_WITHOUT_APP_DATA {
|
||||
return Err(PusError::RawDataTooShort(raw_data_len));
|
||||
}
|
||||
let sec_header = zc::PusTcSecondaryHeader::from_bytes(
|
||||
&slice[current_idx..current_idx + PUC_TC_SECONDARY_HEADER_LEN],
|
||||
)
|
||||
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||
current_idx += PUC_TC_SECONDARY_HEADER_LEN;
|
||||
let raw_data = &slice[0..total_len];
|
||||
let pus_tc = Self {
|
||||
sp_header,
|
||||
sec_header: PusTcSecondaryHeader::try_from(sec_header).unwrap(),
|
||||
raw_data: Some(raw_data),
|
||||
app_data: user_data_from_raw(current_idx, total_len, raw_data_len, slice)?,
|
||||
calc_crc_on_serialization: false,
|
||||
crc16: Some(crc_from_raw_data(raw_data)?),
|
||||
};
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error(
|
||||
raw_data,
|
||||
pus_tc.crc16.expect("CRC16 invalid"),
|
||||
)?;
|
||||
Ok((pus_tc, total_len))
|
||||
}
|
||||
|
||||
#[deprecated(since = "0.5.2", note = "use raw_bytes() instead")]
|
||||
pub fn raw(&self) -> Option<&'raw_data [u8]> {
|
||||
self.raw_bytes()
|
||||
}
|
||||
|
||||
/// If [Self] was constructed [Self::from_bytes], this function will return the slice it was
|
||||
/// constructed from. Otherwise, [None] will be returned.
|
||||
pub fn raw_bytes(&self) -> Option<&'raw_data [u8]> {
|
||||
self.raw_data
|
||||
}
|
||||
}
|
||||
|
||||
impl SerializablePusPacket for PusTc<'_> {
|
||||
fn len_packed(&self) -> usize {
|
||||
PUS_TC_MIN_LEN_WITHOUT_APP_DATA + self.app_data.len()
|
||||
}
|
||||
|
||||
/// Write the raw PUS byte representation to a provided buffer.
|
||||
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
|
||||
let mut curr_idx = 0;
|
||||
let tc_header_len = size_of::<zc::PusTcSecondaryHeader>();
|
||||
let total_size = self.len_packed();
|
||||
if total_size > slice.len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: slice.len(),
|
||||
expected: total_size,
|
||||
}
|
||||
.into());
|
||||
}
|
||||
self.sp_header.write_to_be_bytes(slice)?;
|
||||
curr_idx += CCSDS_HEADER_LEN;
|
||||
let sec_header = zc::PusTcSecondaryHeader::try_from(self.sec_header).unwrap();
|
||||
sec_header
|
||||
.write_to_bytes(&mut slice[curr_idx..curr_idx + tc_header_len])
|
||||
.ok_or(ByteConversionError::ZeroCopyToError)?;
|
||||
|
||||
curr_idx += tc_header_len;
|
||||
slice[curr_idx..curr_idx + self.app_data.len()].copy_from_slice(self.app_data);
|
||||
curr_idx += self.app_data.len();
|
||||
let crc16 = crc_procedure(
|
||||
self.calc_crc_on_serialization,
|
||||
&self.crc16,
|
||||
0,
|
||||
curr_idx,
|
||||
slice,
|
||||
)?;
|
||||
slice[curr_idx..curr_idx + 2].copy_from_slice(crc16.to_be_bytes().as_slice());
|
||||
curr_idx += 2;
|
||||
Ok(curr_idx)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for PusTc<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.sp_header == other.sp_header
|
||||
&& self.sec_header == other.sec_header
|
||||
&& self.app_data == other.app_data
|
||||
}
|
||||
}
|
||||
|
||||
impl CcsdsPacket for PusTc<'_> {
|
||||
ccsds_impl!();
|
||||
}
|
||||
|
||||
impl PusPacket for PusTc<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
});
|
||||
|
||||
fn user_data(&self) -> &[u8] {
|
||||
self.app_data
|
||||
}
|
||||
|
||||
fn crc16(&self) -> Option<u16> {
|
||||
self.crc16
|
||||
}
|
||||
}
|
||||
|
||||
impl GenericPusTcSecondaryHeader for PusTc<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
fn source_id(&self) -> u16;
|
||||
fn ack_flags(&self) -> u8;
|
||||
});
|
||||
}
|
||||
|
||||
impl IsPusTelecommand for PusTc<'_> {}
|
||||
}
|
||||
|
||||
/// This class can be used to create PUS C telecommand packet. It is the primary data structure to
|
||||
/// generate the raw byte representation of a PUS telecommand.
|
||||
///
|
||||
/// This class also derives the [serde::Serialize] and [serde::Deserialize] trait if the
|
||||
/// [serde] feature is used, which allows to send around TC packets in a raw byte format using a
|
||||
/// serde provider like [postcard](https://docs.rs/postcard/latest/postcard/).
|
||||
///
|
||||
/// There is no spare bytes support yet.
|
||||
///
|
||||
/// # Lifetimes
|
||||
///
|
||||
/// * `'raw_data` - If the TC is not constructed from a raw slice, this will be the life time of
|
||||
/// a buffer where the user provided application data will be serialized into. If it
|
||||
/// is, this is the lifetime of the raw byte slice it is constructed from.
|
||||
#[derive(Eq, Copy, Clone, Debug)]
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct PusTc<'raw_data> {
|
||||
pub struct PusTcCreator<'raw_data> {
|
||||
sp_header: SpHeader,
|
||||
pub sec_header: PusTcSecondaryHeader,
|
||||
/// If this is set to false, a manual call to [PusTc::calc_own_crc16] or
|
||||
/// [PusTc::update_packet_fields] is necessary for the serialized or cached CRC16 to be valid.
|
||||
pub calc_crc_on_serialization: bool,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
raw_data: Option<&'raw_data [u8]>,
|
||||
app_data: Option<&'raw_data [u8]>,
|
||||
crc16: Option<u16>,
|
||||
app_data: &'raw_data [u8],
|
||||
}
|
||||
|
||||
impl<'raw_data> PusTc<'raw_data> {
|
||||
impl<'raw_data> PusTcCreator<'raw_data> {
|
||||
/// Generates a new struct instance.
|
||||
///
|
||||
/// # Arguments
|
||||
@ -255,13 +565,10 @@ impl<'raw_data> PusTc<'raw_data> {
|
||||
) -> Self {
|
||||
sp_header.set_packet_type(PacketType::Tc);
|
||||
sp_header.set_sec_header_flag();
|
||||
let mut pus_tc = PusTc {
|
||||
let mut pus_tc = Self {
|
||||
sp_header: *sp_header,
|
||||
raw_data: None,
|
||||
app_data,
|
||||
app_data: app_data.unwrap_or(&[]),
|
||||
sec_header,
|
||||
calc_crc_on_serialization: true,
|
||||
crc16: None,
|
||||
};
|
||||
if set_ccsds_len {
|
||||
pus_tc.update_ccsds_data_len();
|
||||
@ -269,8 +576,8 @@ impl<'raw_data> PusTc<'raw_data> {
|
||||
pus_tc
|
||||
}
|
||||
|
||||
/// Simplified version of the [PusTc::new] function which allows to only specify service and
|
||||
/// subservice instead of the full PUS TC secondary header.
|
||||
/// Simplified version of the [PusTcCreator::new] function which allows to only specify service
|
||||
/// and subservice instead of the full PUS TC secondary header.
|
||||
pub fn new_simple(
|
||||
sph: &mut SpHeader,
|
||||
service: u8,
|
||||
@ -317,22 +624,14 @@ impl<'raw_data> PusTc<'raw_data> {
|
||||
|
||||
/// This function should be called before the TC packet is serialized if
|
||||
/// [PusTc::calc_crc_on_serialization] is set to False. It will calculate and cache the CRC16.
|
||||
pub fn calc_own_crc16(&mut self) {
|
||||
pub fn calc_own_crc16(&self) -> u16 {
|
||||
let mut digest = CRC_CCITT_FALSE.digest();
|
||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||
digest.update(sph_zc.as_bytes());
|
||||
let pus_tc_header = zc::PusTcSecondaryHeader::try_from(self.sec_header).unwrap();
|
||||
digest.update(pus_tc_header.as_bytes());
|
||||
if let Some(app_data) = self.app_data {
|
||||
digest.update(app_data);
|
||||
}
|
||||
self.crc16 = Some(digest.finalize())
|
||||
}
|
||||
|
||||
/// This helper function calls both [PusTc::update_ccsds_data_len] and [PusTc::calc_own_crc16].
|
||||
pub fn update_packet_fields(&mut self) {
|
||||
self.update_ccsds_data_len();
|
||||
self.calc_own_crc16();
|
||||
digest.update(self.app_data);
|
||||
digest.finalize()
|
||||
}
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
@ -340,35 +639,113 @@ impl<'raw_data> PusTc<'raw_data> {
|
||||
pub fn append_to_vec(&self, vec: &mut Vec<u8>) -> Result<usize, PusError> {
|
||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||
let mut appended_len = PUS_TC_MIN_LEN_WITHOUT_APP_DATA;
|
||||
if let Some(app_data) = self.app_data {
|
||||
appended_len += app_data.len();
|
||||
};
|
||||
appended_len += self.app_data.len();
|
||||
let start_idx = vec.len();
|
||||
let mut ser_len = 0;
|
||||
vec.extend_from_slice(sph_zc.as_bytes());
|
||||
ser_len += sph_zc.as_bytes().len();
|
||||
// The PUS version is hardcoded to PUS C
|
||||
let pus_tc_header = zc::PusTcSecondaryHeader::try_from(self.sec_header).unwrap();
|
||||
vec.extend_from_slice(pus_tc_header.as_bytes());
|
||||
ser_len += pus_tc_header.as_bytes().len();
|
||||
if let Some(app_data) = self.app_data {
|
||||
vec.extend_from_slice(app_data);
|
||||
ser_len += app_data.len();
|
||||
}
|
||||
let crc16 = crc_procedure(
|
||||
self.calc_crc_on_serialization,
|
||||
&self.crc16,
|
||||
start_idx,
|
||||
ser_len,
|
||||
&vec[start_idx..ser_len],
|
||||
)?;
|
||||
vec.extend_from_slice(crc16.to_be_bytes().as_slice());
|
||||
vec.extend_from_slice(self.app_data);
|
||||
let mut digest = CRC_CCITT_FALSE.digest();
|
||||
digest.update(&vec[start_idx..start_idx + appended_len - 2]);
|
||||
vec.extend_from_slice(&digest.finalize().to_be_bytes());
|
||||
Ok(appended_len)
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a [PusTc] instance from a raw slice. On success, it returns a tuple containing
|
||||
impl SerializablePusPacket for PusTcCreator<'_> {
|
||||
fn len_packed(&self) -> usize {
|
||||
PUS_TC_MIN_LEN_WITHOUT_APP_DATA + self.app_data.len()
|
||||
}
|
||||
|
||||
/// Write the raw PUS byte representation to a provided buffer.
|
||||
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
|
||||
let mut curr_idx = 0;
|
||||
let tc_header_len = size_of::<zc::PusTcSecondaryHeader>();
|
||||
let total_size = self.len_packed();
|
||||
if total_size > slice.len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: slice.len(),
|
||||
expected: total_size,
|
||||
}
|
||||
.into());
|
||||
}
|
||||
self.sp_header.write_to_be_bytes(slice)?;
|
||||
curr_idx += CCSDS_HEADER_LEN;
|
||||
let sec_header = zc::PusTcSecondaryHeader::try_from(self.sec_header).unwrap();
|
||||
sec_header
|
||||
.write_to_bytes(&mut slice[curr_idx..curr_idx + tc_header_len])
|
||||
.ok_or(ByteConversionError::ZeroCopyToError)?;
|
||||
|
||||
curr_idx += tc_header_len;
|
||||
slice[curr_idx..curr_idx + self.app_data.len()].copy_from_slice(self.app_data);
|
||||
curr_idx += self.app_data.len();
|
||||
let mut digest = CRC_CCITT_FALSE.digest();
|
||||
digest.update(&slice[0..curr_idx]);
|
||||
slice[curr_idx..curr_idx + 2].copy_from_slice(&digest.finalize().to_be_bytes());
|
||||
curr_idx += 2;
|
||||
Ok(curr_idx)
|
||||
}
|
||||
}
|
||||
|
||||
impl CcsdsPacket for PusTcCreator<'_> {
|
||||
ccsds_impl!();
|
||||
}
|
||||
|
||||
impl PusPacket for PusTcCreator<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
});
|
||||
|
||||
fn user_data(&self) -> &[u8] {
|
||||
self.app_data
|
||||
}
|
||||
|
||||
fn crc16(&self) -> Option<u16> {
|
||||
Some(self.calc_own_crc16())
|
||||
}
|
||||
}
|
||||
|
||||
impl GenericPusTcSecondaryHeader for PusTcCreator<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
fn source_id(&self) -> u16;
|
||||
fn ack_flags(&self) -> u8;
|
||||
});
|
||||
}
|
||||
|
||||
impl IsPusTelecommand for PusTcCreator<'_> {}
|
||||
|
||||
/// This class can be used to read a PUS TC telecommand from raw memory.
|
||||
///
|
||||
/// This class also derives the [serde::Serialize] and [serde::Deserialize] trait if the
|
||||
/// [serde] feature is used, which allows to send around TC packets in a raw byte format using a
|
||||
/// serde provider like [postcard](https://docs.rs/postcard/latest/postcard/).
|
||||
///
|
||||
/// There is no spare bytes support yet.
|
||||
///
|
||||
/// # Lifetimes
|
||||
///
|
||||
/// * `'raw_data` - Lifetime of the provided raw slice.
|
||||
#[derive(Eq, Copy, Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct PusTcReader<'raw_data> {
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
raw_data: &'raw_data [u8],
|
||||
sp_header: SpHeader,
|
||||
sec_header: PusTcSecondaryHeader,
|
||||
app_data: &'raw_data [u8],
|
||||
crc16: u16,
|
||||
}
|
||||
|
||||
impl<'raw_data> PusTcReader<'raw_data> {
|
||||
/// Create a [PusTcReader] instance from a raw slice. On success, it returns a tuple containing
|
||||
/// the instance and the found byte length of the packet.
|
||||
pub fn from_bytes(slice: &'raw_data [u8]) -> Result<(Self, usize), PusError> {
|
||||
pub fn new(slice: &'raw_data [u8]) -> Result<(Self, usize), PusError> {
|
||||
let raw_data_len = slice.len();
|
||||
if raw_data_len < PUS_TC_MIN_LEN_WITHOUT_APP_DATA {
|
||||
return Err(PusError::RawDataTooShort(raw_data_len));
|
||||
@ -386,111 +763,61 @@ impl<'raw_data> PusTc<'raw_data> {
|
||||
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||
current_idx += PUC_TC_SECONDARY_HEADER_LEN;
|
||||
let raw_data = &slice[0..total_len];
|
||||
let pus_tc = PusTc {
|
||||
let pus_tc = Self {
|
||||
sp_header,
|
||||
sec_header: PusTcSecondaryHeader::try_from(sec_header).unwrap(),
|
||||
raw_data: Some(raw_data),
|
||||
app_data: user_data_from_raw(current_idx, total_len, raw_data_len, slice)?,
|
||||
calc_crc_on_serialization: false,
|
||||
crc16: Some(crc_from_raw_data(raw_data)?),
|
||||
};
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error(
|
||||
raw_data,
|
||||
pus_tc.crc16.expect("CRC16 invalid"),
|
||||
)?;
|
||||
app_data: user_data_from_raw(current_idx, total_len, raw_data_len, slice)?,
|
||||
crc16: crc_from_raw_data(raw_data)?,
|
||||
};
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error(raw_data, pus_tc.crc16)?;
|
||||
Ok((pus_tc, total_len))
|
||||
}
|
||||
|
||||
#[deprecated(since = "0.5.2", note = "use raw_bytes() instead")]
|
||||
pub fn raw(&self) -> Option<&'raw_data [u8]> {
|
||||
self.raw_bytes()
|
||||
pub fn app_data(&self) -> &[u8] {
|
||||
self.user_data()
|
||||
}
|
||||
|
||||
/// If [Self] was constructed [Self::from_bytes], this function will return the slice it was
|
||||
/// constructed from. Otherwise, [None] will be returned.
|
||||
pub fn raw_bytes(&self) -> Option<&'raw_data [u8]> {
|
||||
pub fn raw_data(&self) -> &[u8] {
|
||||
self.raw_data
|
||||
}
|
||||
}
|
||||
|
||||
impl SerializablePusPacket for PusTc<'_> {
|
||||
fn len_packed(&self) -> usize {
|
||||
let mut length = PUS_TC_MIN_LEN_WITHOUT_APP_DATA;
|
||||
if let Some(app_data) = self.app_data {
|
||||
length += app_data.len();
|
||||
}
|
||||
length
|
||||
pub fn len_packed(&self) -> usize {
|
||||
self.sp_header.total_len()
|
||||
}
|
||||
|
||||
/// Write the raw PUS byte representation to a provided buffer.
|
||||
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
|
||||
let mut curr_idx = 0;
|
||||
let tc_header_len = size_of::<zc::PusTcSecondaryHeader>();
|
||||
let total_size = self.len_packed();
|
||||
if total_size > slice.len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
found: slice.len(),
|
||||
expected: total_size,
|
||||
})
|
||||
.into());
|
||||
}
|
||||
self.sp_header.write_to_be_bytes(slice)?;
|
||||
curr_idx += CCSDS_HEADER_LEN;
|
||||
let sec_header = zc::PusTcSecondaryHeader::try_from(self.sec_header).unwrap();
|
||||
sec_header
|
||||
.write_to_bytes(&mut slice[curr_idx..curr_idx + tc_header_len])
|
||||
.ok_or(ByteConversionError::ZeroCopyToError)?;
|
||||
|
||||
curr_idx += tc_header_len;
|
||||
if let Some(app_data) = self.app_data {
|
||||
slice[curr_idx..curr_idx + app_data.len()].copy_from_slice(app_data);
|
||||
curr_idx += app_data.len();
|
||||
}
|
||||
let crc16 = crc_procedure(
|
||||
self.calc_crc_on_serialization,
|
||||
&self.crc16,
|
||||
0,
|
||||
curr_idx,
|
||||
slice,
|
||||
)?;
|
||||
slice[curr_idx..curr_idx + 2].copy_from_slice(crc16.to_be_bytes().as_slice());
|
||||
curr_idx += 2;
|
||||
Ok(curr_idx)
|
||||
pub fn sp_header(&self) -> &SpHeader {
|
||||
&self.sp_header
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for PusTc<'_> {
|
||||
impl PartialEq for PusTcReader<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.sp_header == other.sp_header
|
||||
&& self.sec_header == other.sec_header
|
||||
&& self.app_data == other.app_data
|
||||
self.raw_data == other.raw_data
|
||||
}
|
||||
}
|
||||
|
||||
//noinspection RsTraitImplementation
|
||||
impl CcsdsPacket for PusTc<'_> {
|
||||
impl CcsdsPacket for PusTcReader<'_> {
|
||||
ccsds_impl!();
|
||||
}
|
||||
|
||||
//noinspection RsTraitImplementation
|
||||
impl PusPacket for PusTc<'_> {
|
||||
impl PusPacket for PusTcReader<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
});
|
||||
|
||||
fn user_data(&self) -> Option<&[u8]> {
|
||||
fn user_data(&self) -> &[u8] {
|
||||
self.app_data
|
||||
}
|
||||
|
||||
fn crc16(&self) -> Option<u16> {
|
||||
self.crc16
|
||||
Some(self.crc16)
|
||||
}
|
||||
}
|
||||
|
||||
//noinspection RsTraitImplementation
|
||||
impl GenericPusTcSecondaryHeader for PusTc<'_> {
|
||||
impl GenericPusTcSecondaryHeader for PusTcReader<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
@ -500,36 +827,54 @@ impl GenericPusTcSecondaryHeader for PusTc<'_> {
|
||||
});
|
||||
}
|
||||
|
||||
impl IsPusTelecommand for PusTcReader<'_> {}
|
||||
|
||||
impl PartialEq<PusTcCreator<'_>> for PusTcReader<'_> {
|
||||
fn eq(&self, other: &PusTcCreator) -> bool {
|
||||
self.sp_header == other.sp_header
|
||||
&& self.sec_header == other.sec_header
|
||||
&& self.app_data == other.app_data
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq<PusTcReader<'_>> for PusTcCreator<'_> {
|
||||
fn eq(&self, other: &PusTcReader) -> bool {
|
||||
self.sp_header == other.sp_header
|
||||
&& self.sec_header == other.sec_header
|
||||
&& self.app_data == other.app_data
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "std"))]
|
||||
mod tests {
|
||||
use crate::ecss::tc::{
|
||||
GenericPusTcSecondaryHeader, PusTcCreator, PusTcReader, PusTcSecondaryHeader, ACK_ALL,
|
||||
};
|
||||
use crate::ecss::PusVersion::PusC;
|
||||
use crate::ecss::{PusError, PusPacket, SerializablePusPacket};
|
||||
use crate::tc::ACK_ALL;
|
||||
use crate::tc::{GenericPusTcSecondaryHeader, PusTc, PusTcSecondaryHeader};
|
||||
use crate::{ByteConversionError, SpHeader};
|
||||
use crate::{CcsdsPacket, SequenceFlags};
|
||||
use alloc::vec::Vec;
|
||||
|
||||
fn base_ping_tc_full_ctor() -> PusTc<'static> {
|
||||
fn base_ping_tc_full_ctor() -> PusTcCreator<'static> {
|
||||
let mut sph = SpHeader::tc_unseg(0x02, 0x34, 0).unwrap();
|
||||
let tc_header = PusTcSecondaryHeader::new_simple(17, 1);
|
||||
PusTc::new(&mut sph, tc_header, None, true)
|
||||
PusTcCreator::new(&mut sph, tc_header, None, true)
|
||||
}
|
||||
|
||||
fn base_ping_tc_simple_ctor() -> PusTc<'static> {
|
||||
fn base_ping_tc_simple_ctor() -> PusTcCreator<'static> {
|
||||
let mut sph = SpHeader::tc_unseg(0x02, 0x34, 0).unwrap();
|
||||
PusTc::new_simple(&mut sph, 17, 1, None, true)
|
||||
PusTcCreator::new_simple(&mut sph, 17, 1, None, true)
|
||||
}
|
||||
|
||||
fn base_ping_tc_simple_ctor_with_app_data(app_data: &'static [u8]) -> PusTc<'static> {
|
||||
fn base_ping_tc_simple_ctor_with_app_data(app_data: &'static [u8]) -> PusTcCreator<'static> {
|
||||
let mut sph = SpHeader::tc_unseg(0x02, 0x34, 0).unwrap();
|
||||
PusTc::new_simple(&mut sph, 17, 1, Some(app_data), true)
|
||||
PusTcCreator::new_simple(&mut sph, 17, 1, Some(app_data), true)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tc_fields() {
|
||||
let pus_tc = base_ping_tc_full_ctor();
|
||||
assert_eq!(pus_tc.crc16(), None);
|
||||
verify_test_tc(&pus_tc, false, 13);
|
||||
}
|
||||
|
||||
@ -552,10 +897,10 @@ mod tests {
|
||||
.expect("Error writing TC to buffer");
|
||||
assert_eq!(size, 13);
|
||||
let (tc_from_raw, size) =
|
||||
PusTc::from_bytes(&test_buf).expect("Creating PUS TC struct from raw buffer failed");
|
||||
PusTcReader::new(&test_buf).expect("Creating PUS TC struct from raw buffer failed");
|
||||
assert_eq!(size, 13);
|
||||
verify_test_tc(&tc_from_raw, false, 13);
|
||||
assert!(tc_from_raw.user_data().is_none());
|
||||
verify_test_tc_with_reader(&tc_from_raw, false, 13);
|
||||
assert!(tc_from_raw.user_data().is_empty());
|
||||
verify_test_tc_raw(&test_buf);
|
||||
verify_crc_no_app_data(&test_buf);
|
||||
}
|
||||
@ -563,10 +908,9 @@ mod tests {
|
||||
#[test]
|
||||
fn test_update_func() {
|
||||
let mut sph = SpHeader::tc_unseg(0x02, 0x34, 0).unwrap();
|
||||
let mut tc = PusTc::new_simple(&mut sph, 17, 1, None, false);
|
||||
tc.calc_crc_on_serialization = false;
|
||||
let mut tc = PusTcCreator::new_simple(&mut sph, 17, 1, None, false);
|
||||
assert_eq!(tc.data_len(), 0);
|
||||
tc.update_packet_fields();
|
||||
tc.update_ccsds_data_len();
|
||||
assert_eq!(tc.data_len(), 6);
|
||||
}
|
||||
#[test]
|
||||
@ -578,10 +922,10 @@ mod tests {
|
||||
.expect("Error writing TC to buffer");
|
||||
assert_eq!(size, 16);
|
||||
let (tc_from_raw, size) =
|
||||
PusTc::from_bytes(&test_buf).expect("Creating PUS TC struct from raw buffer failed");
|
||||
PusTcReader::new(&test_buf).expect("Creating PUS TC struct from raw buffer failed");
|
||||
assert_eq!(size, 16);
|
||||
verify_test_tc(&tc_from_raw, true, 16);
|
||||
let user_data = tc_from_raw.user_data().unwrap();
|
||||
verify_test_tc_with_reader(&tc_from_raw, true, 16);
|
||||
let user_data = tc_from_raw.user_data();
|
||||
assert_eq!(user_data[0], 1);
|
||||
assert_eq!(user_data[1], 2);
|
||||
assert_eq!(user_data[2], 3);
|
||||
@ -607,7 +951,7 @@ mod tests {
|
||||
.write_to_bytes(test_buf.as_mut_slice())
|
||||
.expect("Error writing TC to buffer");
|
||||
test_buf[12] = 0;
|
||||
let res = PusTc::from_bytes(&test_buf);
|
||||
let res = PusTcReader::new(&test_buf);
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
assert!(matches!(err, PusError::IncorrectCrc { .. }));
|
||||
@ -615,8 +959,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_manual_crc_calculation() {
|
||||
let mut pus_tc = base_ping_tc_simple_ctor();
|
||||
pus_tc.calc_crc_on_serialization = false;
|
||||
let pus_tc = base_ping_tc_simple_ctor();
|
||||
let mut test_buf: [u8; 32] = [0; 32];
|
||||
pus_tc.calc_own_crc16();
|
||||
pus_tc
|
||||
@ -626,17 +969,6 @@ mod tests {
|
||||
verify_crc_no_app_data(&test_buf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_manual_crc_calculation_no_calc_call() {
|
||||
let mut pus_tc = base_ping_tc_simple_ctor();
|
||||
pus_tc.calc_crc_on_serialization = false;
|
||||
let mut test_buf: [u8; 32] = [0; 32];
|
||||
let res = pus_tc.write_to_bytes(test_buf.as_mut_slice());
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
assert!(matches!(err, PusError::CrcCalculationMissing { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_application_data_vec() {
|
||||
let pus_tc = base_ping_tc_simple_ctor_with_app_data(&[1, 2, 3]);
|
||||
@ -659,10 +991,10 @@ mod tests {
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
PusError::ByteConversionError(err) => match err {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.expected, pus_tc.len_packed());
|
||||
assert_eq!(missmatch.found, 12);
|
||||
PusError::ByteConversion(err) => match err {
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(expected, pus_tc.len_packed());
|
||||
assert_eq!(found, 12);
|
||||
}
|
||||
_ => panic!("Unexpected error"),
|
||||
},
|
||||
@ -712,24 +1044,37 @@ mod tests {
|
||||
assert_eq!(test_buf[10], 0xff);
|
||||
}
|
||||
|
||||
fn verify_test_tc(tc: &PusTc, has_user_data: bool, exp_full_len: usize) {
|
||||
fn verify_test_tc(tc: &PusTcCreator, has_user_data: bool, exp_full_len: usize) {
|
||||
verify_test_tc_generic(tc);
|
||||
if !has_user_data {
|
||||
assert!(tc.user_data().is_empty());
|
||||
}
|
||||
let mut comp_header = SpHeader::tc_unseg(0x02, 0x34, exp_full_len as u16 - 7).unwrap();
|
||||
comp_header.set_sec_header_flag();
|
||||
assert_eq!(*tc.sp_header(), comp_header);
|
||||
}
|
||||
|
||||
fn verify_test_tc_with_reader(tc: &PusTcReader, has_user_data: bool, exp_full_len: usize) {
|
||||
verify_test_tc_generic(tc);
|
||||
if !has_user_data {
|
||||
assert!(tc.user_data().is_empty());
|
||||
}
|
||||
assert_eq!(tc.len_packed(), exp_full_len);
|
||||
let mut comp_header = SpHeader::tc_unseg(0x02, 0x34, exp_full_len as u16 - 7).unwrap();
|
||||
comp_header.set_sec_header_flag();
|
||||
assert_eq!(*tc.sp_header(), comp_header);
|
||||
}
|
||||
|
||||
fn verify_test_tc_generic(tc: &(impl CcsdsPacket + PusPacket + GenericPusTcSecondaryHeader)) {
|
||||
assert_eq!(PusPacket::service(tc), 17);
|
||||
assert_eq!(PusPacket::subservice(tc), 1);
|
||||
assert!(tc.sec_header_flag());
|
||||
assert_eq!(PusPacket::pus_version(tc), PusC);
|
||||
if !has_user_data {
|
||||
assert_eq!(tc.user_data(), None);
|
||||
}
|
||||
assert_eq!(tc.seq_count(), 0x34);
|
||||
assert_eq!(tc.source_id(), 0);
|
||||
assert_eq!(tc.apid(), 0x02);
|
||||
assert_eq!(tc.ack_flags(), ACK_ALL);
|
||||
assert_eq!(tc.len_packed(), exp_full_len);
|
||||
let mut comp_header = SpHeader::tc_unseg(0x02, 0x34, exp_full_len as u16 - 7).unwrap();
|
||||
comp_header.set_sec_header_flag();
|
||||
assert_eq!(tc.sp_header, comp_header);
|
||||
}
|
||||
|
||||
fn verify_test_tc_raw(slice: &impl AsRef<[u8]>) {
|
||||
// Reference comparison implementation:
|
||||
// https://github.com/us-irs/py-spacepackets/blob/v0.13.0/tests/ecss/test_pus_tc.py
|
||||
@ -777,6 +1122,7 @@ mod tests {
|
||||
let pus_tc = base_ping_tc_simple_ctor();
|
||||
let mut buf = [0; 32];
|
||||
pus_tc.write_to_bytes(&mut buf).unwrap();
|
||||
assert_eq!(pus_tc, PusTc::from_bytes(&buf).unwrap().0);
|
||||
assert_eq!(pus_tc, PusTcReader::new(&buf).unwrap().0);
|
||||
assert_eq!(PusTcReader::new(&buf).unwrap().0, pus_tc);
|
||||
}
|
||||
}
|
@ -1,13 +1,13 @@
|
||||
//! This module contains all components required to create a ECSS PUS C telemetry packets according
|
||||
//! to [ECSS-E-ST-70-41C](https://ecss.nl/standard/ecss-e-st-70-41c-space-engineering-telemetry-and-telecommand-packet-utilization-15-april-2016/).
|
||||
use crate::ecss::{
|
||||
calc_pus_crc16, ccsds_impl, crc_from_raw_data, crc_procedure, sp_header_impls,
|
||||
user_data_from_raw, verify_crc16_ccitt_false_from_raw_to_pus_error, CrcType, PusError,
|
||||
PusPacket, PusVersion, SerializablePusPacket,
|
||||
calc_pus_crc16, ccsds_impl, crc_from_raw_data, sp_header_impls, user_data_from_raw,
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error, CrcType, PusError, PusPacket, PusVersion,
|
||||
SerializablePusPacket,
|
||||
};
|
||||
use crate::{
|
||||
ByteConversionError, CcsdsPacket, PacketType, SequenceFlags, SizeMissmatch, SpHeader,
|
||||
CCSDS_HEADER_LEN, CRC_CCITT_FALSE, MAX_APID, MAX_SEQ_COUNT,
|
||||
ByteConversionError, CcsdsPacket, PacketType, SequenceFlags, SpHeader, CCSDS_HEADER_LEN,
|
||||
CRC_CCITT_FALSE, MAX_APID, MAX_SEQ_COUNT,
|
||||
};
|
||||
use core::mem::size_of;
|
||||
#[cfg(feature = "serde")]
|
||||
@ -18,6 +18,11 @@ use zerocopy::AsBytes;
|
||||
use alloc::vec::Vec;
|
||||
use delegate::delegate;
|
||||
|
||||
use crate::time::{TimeWriter, TimestampError};
|
||||
pub use legacy_tm::*;
|
||||
|
||||
pub trait IsPusTelemetry {}
|
||||
|
||||
/// Length without timestamp
|
||||
pub const PUC_TM_MIN_SEC_HEADER_LEN: usize = 7;
|
||||
pub const PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA: usize =
|
||||
@ -35,9 +40,9 @@ pub trait GenericPusTmSecondaryHeader {
|
||||
pub mod zc {
|
||||
use super::GenericPusTmSecondaryHeader;
|
||||
use crate::ecss::{PusError, PusVersion};
|
||||
use zerocopy::{AsBytes, FromBytes, NetworkEndian, Unaligned, U16};
|
||||
use zerocopy::{AsBytes, FromBytes, FromZeroes, NetworkEndian, Unaligned, U16};
|
||||
|
||||
#[derive(FromBytes, AsBytes, Unaligned)]
|
||||
#[derive(FromBytes, FromZeroes, AsBytes, Unaligned)]
|
||||
#[repr(C)]
|
||||
pub struct PusTmSecHeaderWithoutTimestamp {
|
||||
pus_version_and_sc_time_ref_status: u8,
|
||||
@ -49,12 +54,12 @@ pub mod zc {
|
||||
|
||||
pub struct PusTmSecHeader<'slice> {
|
||||
pub(crate) zc_header: PusTmSecHeaderWithoutTimestamp,
|
||||
pub(crate) timestamp: Option<&'slice [u8]>,
|
||||
pub(crate) timestamp: &'slice [u8],
|
||||
}
|
||||
|
||||
impl TryFrom<crate::tm::PusTmSecondaryHeader<'_>> for PusTmSecHeaderWithoutTimestamp {
|
||||
impl TryFrom<crate::ecss::tm::PusTmSecondaryHeader<'_>> for PusTmSecHeaderWithoutTimestamp {
|
||||
type Error = PusError;
|
||||
fn try_from(header: crate::tm::PusTmSecondaryHeader) -> Result<Self, Self::Error> {
|
||||
fn try_from(header: crate::ecss::tm::PusTmSecondaryHeader) -> Result<Self, Self::Error> {
|
||||
if header.pus_version != PusVersion::PusC {
|
||||
return Err(PusError::VersionNotSupported(header.pus_version));
|
||||
}
|
||||
@ -116,7 +121,7 @@ pub struct PusTmSecondaryHeader<'stamp> {
|
||||
pub subservice: u8,
|
||||
pub msg_counter: u16,
|
||||
pub dest_id: u16,
|
||||
pub timestamp: Option<&'stamp [u8]>,
|
||||
pub timestamp: &'stamp [u8],
|
||||
}
|
||||
|
||||
impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
@ -143,7 +148,7 @@ impl<'stamp> PusTmSecondaryHeader<'stamp> {
|
||||
subservice,
|
||||
msg_counter,
|
||||
dest_id,
|
||||
timestamp,
|
||||
timestamp: timestamp.unwrap_or(&[]),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -190,8 +195,322 @@ impl<'slice> TryFrom<zc::PusTmSecHeader<'slice>> for PusTmSecondaryHeader<'slice
|
||||
}
|
||||
}
|
||||
|
||||
pub mod legacy_tm {
|
||||
use crate::ecss::tm::{
|
||||
zc, GenericPusTmSecondaryHeader, IsPusTelemetry, PusTmSecondaryHeader,
|
||||
PUC_TM_MIN_SEC_HEADER_LEN, PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA,
|
||||
};
|
||||
use crate::ecss::PusVersion;
|
||||
use crate::ecss::{
|
||||
ccsds_impl, crc_from_raw_data, crc_procedure, sp_header_impls, user_data_from_raw,
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error, PusError, PusPacket, SerializablePusPacket,
|
||||
CCSDS_HEADER_LEN,
|
||||
};
|
||||
use crate::SequenceFlags;
|
||||
use crate::{ByteConversionError, CcsdsPacket, PacketType, SpHeader, CRC_CCITT_FALSE};
|
||||
use core::mem::size_of;
|
||||
use zerocopy::AsBytes;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
use alloc::vec::Vec;
|
||||
use delegate::delegate;
|
||||
|
||||
/// This class models the PUS C telemetry packet. It is the primary data structure to generate the
|
||||
/// raw byte representation of PUS telemetry or to deserialize from one from raw bytes.
|
||||
///
|
||||
/// This class also derives the [serde::Serialize] and [serde::Deserialize] trait if the [serde]
|
||||
/// feature is used which allows to send around TM packets in a raw byte format using a serde
|
||||
/// provider like [postcard](https://docs.rs/postcard/latest/postcard/).
|
||||
///
|
||||
/// There is no spare bytes support yet.
|
||||
///
|
||||
/// # Lifetimes
|
||||
///
|
||||
/// * `'raw_data` - If the TM is not constructed from a raw slice, this will be the life time of
|
||||
/// a buffer where the user provided time stamp and source data will be serialized into. If it
|
||||
/// is, this is the lifetime of the raw byte slice it is constructed from.
|
||||
#[derive(Eq, Debug, Copy, Clone)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct PusTm<'raw_data> {
|
||||
pub sp_header: SpHeader,
|
||||
pub sec_header: PusTmSecondaryHeader<'raw_data>,
|
||||
/// If this is set to false, a manual call to [PusTm::calc_own_crc16] or
|
||||
/// [PusTm::update_packet_fields] is necessary for the serialized or cached CRC16 to be valid.
|
||||
pub calc_crc_on_serialization: bool,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
raw_data: Option<&'raw_data [u8]>,
|
||||
source_data: &'raw_data [u8],
|
||||
crc16: Option<u16>,
|
||||
}
|
||||
|
||||
impl<'raw_data> PusTm<'raw_data> {
|
||||
/// Generates a new struct instance.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `sp_header` - Space packet header information. The correct packet type will be set
|
||||
/// automatically
|
||||
/// * `sec_header` - Information contained in the secondary header, including the service
|
||||
/// and subservice type
|
||||
/// * `app_data` - Custom application data
|
||||
/// * `set_ccsds_len` - Can be used to automatically update the CCSDS space packet data length
|
||||
/// field. If this is not set to true, [PusTm::update_ccsds_data_len] can be called to set
|
||||
/// the correct value to this field manually
|
||||
#[deprecated(
|
||||
since = "0.7.0",
|
||||
note = "Use specialized PusTmCreator or PusTmReader classes instead"
|
||||
)]
|
||||
pub fn new(
|
||||
sp_header: &mut SpHeader,
|
||||
sec_header: PusTmSecondaryHeader<'raw_data>,
|
||||
source_data: Option<&'raw_data [u8]>,
|
||||
set_ccsds_len: bool,
|
||||
) -> Self {
|
||||
sp_header.set_packet_type(PacketType::Tm);
|
||||
sp_header.set_sec_header_flag();
|
||||
let mut pus_tm = PusTm {
|
||||
sp_header: *sp_header,
|
||||
raw_data: None,
|
||||
source_data: source_data.unwrap_or(&[]),
|
||||
sec_header,
|
||||
calc_crc_on_serialization: true,
|
||||
crc16: None,
|
||||
};
|
||||
if set_ccsds_len {
|
||||
pus_tm.update_ccsds_data_len();
|
||||
}
|
||||
pus_tm
|
||||
}
|
||||
|
||||
pub fn timestamp(&self) -> &[u8] {
|
||||
self.sec_header.timestamp
|
||||
}
|
||||
|
||||
pub fn source_data(&self) -> &[u8] {
|
||||
self.source_data
|
||||
}
|
||||
|
||||
pub fn set_dest_id(&mut self, dest_id: u16) {
|
||||
self.sec_header.dest_id = dest_id;
|
||||
}
|
||||
|
||||
pub fn set_msg_counter(&mut self, msg_counter: u16) {
|
||||
self.sec_header.msg_counter = msg_counter
|
||||
}
|
||||
|
||||
pub fn set_sc_time_ref_status(&mut self, sc_time_ref_status: u8) {
|
||||
self.sec_header.sc_time_ref_status = sc_time_ref_status & 0b1111;
|
||||
}
|
||||
|
||||
sp_header_impls!();
|
||||
|
||||
/// This is called automatically if the `set_ccsds_len` argument in the [PusTm::new] call was
|
||||
/// used.
|
||||
/// If this was not done or the time stamp or source data is set or changed after construction,
|
||||
/// this function needs to be called to ensure that the data length field of the CCSDS header
|
||||
/// is set correctly
|
||||
pub fn update_ccsds_data_len(&mut self) {
|
||||
self.sp_header.data_len =
|
||||
self.len_packed() as u16 - size_of::<crate::zc::SpHeader>() as u16 - 1;
|
||||
}
|
||||
|
||||
/// This function should be called before the TM packet is serialized if
|
||||
/// [PusTm.calc_crc_on_serialization] is set to False. It will calculate and cache the CRC16.
|
||||
pub fn calc_own_crc16(&mut self) {
|
||||
let mut digest = CRC_CCITT_FALSE.digest();
|
||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||
digest.update(sph_zc.as_bytes());
|
||||
let pus_tc_header =
|
||||
zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
|
||||
digest.update(pus_tc_header.as_bytes());
|
||||
digest.update(self.sec_header.timestamp);
|
||||
digest.update(self.source_data);
|
||||
self.crc16 = Some(digest.finalize())
|
||||
}
|
||||
|
||||
/// This helper function calls both [PusTm.update_ccsds_data_len] and [PusTm.calc_own_crc16]
|
||||
pub fn update_packet_fields(&mut self) {
|
||||
self.update_ccsds_data_len();
|
||||
self.calc_own_crc16();
|
||||
}
|
||||
|
||||
/// Append the raw PUS byte representation to a provided [alloc::vec::Vec]
|
||||
#[cfg(feature = "alloc")]
|
||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
||||
pub fn append_to_vec(&self, vec: &mut Vec<u8>) -> Result<usize, PusError> {
|
||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||
let mut appended_len = PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA;
|
||||
appended_len += self.sec_header.timestamp.len();
|
||||
appended_len += self.source_data.len();
|
||||
let start_idx = vec.len();
|
||||
let mut ser_len = 0;
|
||||
vec.extend_from_slice(sph_zc.as_bytes());
|
||||
ser_len += sph_zc.as_bytes().len();
|
||||
// The PUS version is hardcoded to PUS C
|
||||
let sec_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
|
||||
vec.extend_from_slice(sec_header.as_bytes());
|
||||
ser_len += sec_header.as_bytes().len();
|
||||
ser_len += self.sec_header.timestamp.len();
|
||||
vec.extend_from_slice(self.sec_header.timestamp);
|
||||
vec.extend_from_slice(self.source_data);
|
||||
ser_len += self.source_data.len();
|
||||
let crc16 = crc_procedure(
|
||||
self.calc_crc_on_serialization,
|
||||
&self.crc16,
|
||||
start_idx,
|
||||
ser_len,
|
||||
&vec[start_idx..start_idx + ser_len],
|
||||
)?;
|
||||
vec.extend_from_slice(crc16.to_be_bytes().as_slice());
|
||||
Ok(appended_len)
|
||||
}
|
||||
|
||||
/// Create a [PusTm] instance from a raw slice. On success, it returns a tuple containing
|
||||
/// the instance and the found byte length of the packet. The timestamp length needs to be
|
||||
/// known beforehand.
|
||||
#[deprecated(
|
||||
since = "0.7.0",
|
||||
note = "Use specialized PusTmCreator or PusTmReader classes instead"
|
||||
)]
|
||||
pub fn from_bytes(
|
||||
slice: &'raw_data [u8],
|
||||
timestamp_len: usize,
|
||||
) -> Result<(Self, usize), PusError> {
|
||||
let raw_data_len = slice.len();
|
||||
if raw_data_len < PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA {
|
||||
return Err(PusError::RawDataTooShort(raw_data_len));
|
||||
}
|
||||
let mut current_idx = 0;
|
||||
let (sp_header, _) = SpHeader::from_be_bytes(&slice[0..CCSDS_HEADER_LEN])?;
|
||||
current_idx += 6;
|
||||
let total_len = sp_header.total_len();
|
||||
if raw_data_len < total_len || total_len < PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA {
|
||||
return Err(PusError::RawDataTooShort(raw_data_len));
|
||||
}
|
||||
let sec_header_zc = zc::PusTmSecHeaderWithoutTimestamp::from_bytes(
|
||||
&slice[current_idx..current_idx + PUC_TM_MIN_SEC_HEADER_LEN],
|
||||
)
|
||||
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||
current_idx += PUC_TM_MIN_SEC_HEADER_LEN;
|
||||
let zc_sec_header_wrapper = zc::PusTmSecHeader {
|
||||
zc_header: sec_header_zc,
|
||||
timestamp: &slice[current_idx..current_idx + timestamp_len],
|
||||
};
|
||||
current_idx += timestamp_len;
|
||||
let raw_data = &slice[0..total_len];
|
||||
let pus_tm = PusTm {
|
||||
sp_header,
|
||||
sec_header: PusTmSecondaryHeader::try_from(zc_sec_header_wrapper).unwrap(),
|
||||
raw_data: Some(&slice[0..total_len]),
|
||||
source_data: user_data_from_raw(current_idx, total_len, raw_data_len, slice)?,
|
||||
calc_crc_on_serialization: false,
|
||||
crc16: Some(crc_from_raw_data(raw_data)?),
|
||||
};
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error(
|
||||
raw_data,
|
||||
pus_tm.crc16.expect("CRC16 invalid"),
|
||||
)?;
|
||||
Ok((pus_tm, total_len))
|
||||
}
|
||||
|
||||
/// If [Self] was constructed [Self::from_bytes], this function will return the slice it was
|
||||
/// constructed from. Otherwise, [None] will be returned.
|
||||
pub fn raw_bytes(&self) -> Option<&'raw_data [u8]> {
|
||||
self.raw_data
|
||||
}
|
||||
}
|
||||
|
||||
impl SerializablePusPacket for PusTm<'_> {
|
||||
fn len_packed(&self) -> usize {
|
||||
PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA
|
||||
+ self.sec_header.timestamp.len()
|
||||
+ self.source_data.len()
|
||||
}
|
||||
/// Write the raw PUS byte representation to a provided buffer.
|
||||
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
|
||||
let mut curr_idx = 0;
|
||||
let total_size = self.len_packed();
|
||||
if total_size > slice.len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: slice.len(),
|
||||
expected: total_size,
|
||||
}
|
||||
.into());
|
||||
}
|
||||
self.sp_header
|
||||
.write_to_be_bytes(&mut slice[0..CCSDS_HEADER_LEN])?;
|
||||
curr_idx += CCSDS_HEADER_LEN;
|
||||
let sec_header_len = size_of::<zc::PusTmSecHeaderWithoutTimestamp>();
|
||||
let sec_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
|
||||
sec_header
|
||||
.write_to_bytes(&mut slice[curr_idx..curr_idx + sec_header_len])
|
||||
.ok_or(ByteConversionError::ZeroCopyToError)?;
|
||||
curr_idx += sec_header_len;
|
||||
slice[curr_idx..curr_idx + self.sec_header.timestamp.len()]
|
||||
.copy_from_slice(self.sec_header.timestamp);
|
||||
curr_idx += self.sec_header.timestamp.len();
|
||||
slice[curr_idx..curr_idx + self.source_data.len()].copy_from_slice(self.source_data);
|
||||
curr_idx += self.source_data.len();
|
||||
let crc16 = crc_procedure(
|
||||
self.calc_crc_on_serialization,
|
||||
&self.crc16,
|
||||
0,
|
||||
curr_idx,
|
||||
slice,
|
||||
)?;
|
||||
slice[curr_idx..curr_idx + 2].copy_from_slice(crc16.to_be_bytes().as_slice());
|
||||
curr_idx += 2;
|
||||
Ok(curr_idx)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for PusTm<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.sp_header == other.sp_header
|
||||
&& self.sec_header == other.sec_header
|
||||
&& self.source_data == other.source_data
|
||||
}
|
||||
}
|
||||
|
||||
impl CcsdsPacket for PusTm<'_> {
|
||||
ccsds_impl!();
|
||||
}
|
||||
|
||||
impl PusPacket for PusTm<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
});
|
||||
|
||||
fn user_data(&self) -> &[u8] {
|
||||
self.source_data
|
||||
}
|
||||
|
||||
fn crc16(&self) -> Option<u16> {
|
||||
self.crc16
|
||||
}
|
||||
}
|
||||
|
||||
impl GenericPusTmSecondaryHeader for PusTm<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
fn dest_id(&self) -> u16;
|
||||
fn msg_counter(&self) -> u16;
|
||||
fn sc_time_ref_status(&self) -> u8;
|
||||
});
|
||||
}
|
||||
|
||||
impl IsPusTelemetry for PusTm<'_> {}
|
||||
}
|
||||
|
||||
/// This class models the PUS C telemetry packet. It is the primary data structure to generate the
|
||||
/// raw byte representation of PUS telemetry or to deserialize from one from raw bytes.
|
||||
/// raw byte representation of PUS telemetry.
|
||||
///
|
||||
/// This class also derives the [serde::Serialize] and [serde::Deserialize] trait if the [serde]
|
||||
/// feature is used which allows to send around TM packets in a raw byte format using a serde
|
||||
@ -201,24 +520,19 @@ impl<'slice> TryFrom<zc::PusTmSecHeader<'slice>> for PusTmSecondaryHeader<'slice
|
||||
///
|
||||
/// # Lifetimes
|
||||
///
|
||||
/// * `'raw_data` - If the TM is not constructed from a raw slice, this will be the life time of
|
||||
/// a buffer where the user provided time stamp and source data will be serialized into. If it
|
||||
/// is, this is the lifetime of the raw byte slice it is constructed from.
|
||||
/// * `'raw_data` - This is the lifetime of the user provided time stamp and source data.
|
||||
#[derive(Eq, Debug, Copy, Clone)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct PusTm<'raw_data> {
|
||||
pub struct PusTmCreator<'raw_data> {
|
||||
pub sp_header: SpHeader,
|
||||
pub sec_header: PusTmSecondaryHeader<'raw_data>,
|
||||
source_data: &'raw_data [u8],
|
||||
/// If this is set to false, a manual call to [PusTm::calc_own_crc16] or
|
||||
/// [PusTm::update_packet_fields] is necessary for the serialized or cached CRC16 to be valid.
|
||||
pub calc_crc_on_serialization: bool,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
raw_data: Option<&'raw_data [u8]>,
|
||||
source_data: Option<&'raw_data [u8]>,
|
||||
crc16: Option<u16>,
|
||||
}
|
||||
|
||||
impl<'raw_data> PusTm<'raw_data> {
|
||||
impl<'raw_data> PusTmCreator<'raw_data> {
|
||||
/// Generates a new struct instance.
|
||||
///
|
||||
/// # Arguments
|
||||
@ -239,13 +553,11 @@ impl<'raw_data> PusTm<'raw_data> {
|
||||
) -> Self {
|
||||
sp_header.set_packet_type(PacketType::Tm);
|
||||
sp_header.set_sec_header_flag();
|
||||
let mut pus_tm = PusTm {
|
||||
let mut pus_tm = Self {
|
||||
sp_header: *sp_header,
|
||||
raw_data: None,
|
||||
source_data,
|
||||
source_data: source_data.unwrap_or(&[]),
|
||||
sec_header,
|
||||
calc_crc_on_serialization: true,
|
||||
crc16: None,
|
||||
};
|
||||
if set_ccsds_len {
|
||||
pus_tm.update_ccsds_data_len();
|
||||
@ -253,11 +565,25 @@ impl<'raw_data> PusTm<'raw_data> {
|
||||
pus_tm
|
||||
}
|
||||
|
||||
pub fn timestamp(&self) -> Option<&'raw_data [u8]> {
|
||||
pub fn new_simple(
|
||||
sp_header: &mut SpHeader,
|
||||
service: u8,
|
||||
subservice: u8,
|
||||
time_provider: &impl TimeWriter,
|
||||
stamp_buf: &'raw_data mut [u8],
|
||||
source_data: Option<&'raw_data [u8]>,
|
||||
set_ccsds_len: bool,
|
||||
) -> 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]);
|
||||
Ok(Self::new(sp_header, sec_header, source_data, set_ccsds_len))
|
||||
}
|
||||
pub fn timestamp(&self) -> &[u8] {
|
||||
self.sec_header.timestamp
|
||||
}
|
||||
|
||||
pub fn source_data(&self) -> Option<&'raw_data [u8]> {
|
||||
pub fn source_data(&self) -> &[u8] {
|
||||
self.source_data
|
||||
}
|
||||
|
||||
@ -287,25 +613,20 @@ impl<'raw_data> PusTm<'raw_data> {
|
||||
|
||||
/// This function should be called before the TM packet is serialized if
|
||||
/// [PusTm.calc_crc_on_serialization] is set to False. It will calculate and cache the CRC16.
|
||||
pub fn calc_own_crc16(&mut self) {
|
||||
pub fn calc_own_crc16(&self) -> u16 {
|
||||
let mut digest = CRC_CCITT_FALSE.digest();
|
||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||
digest.update(sph_zc.as_bytes());
|
||||
let pus_tc_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
|
||||
digest.update(pus_tc_header.as_bytes());
|
||||
if let Some(stamp) = self.sec_header.timestamp {
|
||||
digest.update(stamp);
|
||||
}
|
||||
if let Some(src_data) = self.source_data {
|
||||
digest.update(src_data);
|
||||
}
|
||||
self.crc16 = Some(digest.finalize())
|
||||
digest.update(self.sec_header.timestamp);
|
||||
digest.update(self.source_data);
|
||||
digest.finalize()
|
||||
}
|
||||
|
||||
/// This helper function calls both [PusTm.update_ccsds_data_len] and [PusTm.calc_own_crc16]
|
||||
pub fn update_packet_fields(&mut self) {
|
||||
self.update_ccsds_data_len();
|
||||
self.calc_own_crc16();
|
||||
}
|
||||
|
||||
/// Append the raw PUS byte representation to a provided [alloc::vec::Vec]
|
||||
@ -313,47 +634,130 @@ impl<'raw_data> PusTm<'raw_data> {
|
||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
||||
pub fn append_to_vec(&self, vec: &mut Vec<u8>) -> Result<usize, PusError> {
|
||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||
let mut appended_len = PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA;
|
||||
if let Some(timestamp) = self.sec_header.timestamp {
|
||||
appended_len += timestamp.len();
|
||||
}
|
||||
if let Some(src_data) = self.source_data {
|
||||
appended_len += src_data.len();
|
||||
};
|
||||
let mut appended_len = PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA + self.sec_header.timestamp.len();
|
||||
appended_len += self.source_data.len();
|
||||
let start_idx = vec.len();
|
||||
let mut ser_len = 0;
|
||||
vec.extend_from_slice(sph_zc.as_bytes());
|
||||
ser_len += sph_zc.as_bytes().len();
|
||||
// The PUS version is hardcoded to PUS C
|
||||
let sec_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
|
||||
vec.extend_from_slice(sec_header.as_bytes());
|
||||
ser_len += sec_header.as_bytes().len();
|
||||
if let Some(timestamp) = self.sec_header.timestamp {
|
||||
ser_len += timestamp.len();
|
||||
vec.extend_from_slice(timestamp);
|
||||
}
|
||||
if let Some(src_data) = self.source_data {
|
||||
vec.extend_from_slice(src_data);
|
||||
ser_len += src_data.len();
|
||||
}
|
||||
let crc16 = crc_procedure(
|
||||
self.calc_crc_on_serialization,
|
||||
&self.crc16,
|
||||
start_idx,
|
||||
ser_len,
|
||||
&vec[start_idx..start_idx + ser_len],
|
||||
)?;
|
||||
vec.extend_from_slice(crc16.to_be_bytes().as_slice());
|
||||
vec.extend_from_slice(self.sec_header.timestamp);
|
||||
vec.extend_from_slice(self.source_data);
|
||||
let mut digest = CRC_CCITT_FALSE.digest();
|
||||
digest.update(&vec[start_idx..start_idx + appended_len - 2]);
|
||||
vec.extend_from_slice(&digest.finalize().to_be_bytes());
|
||||
Ok(appended_len)
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a [PusTm] instance from a raw slice. On success, it returns a tuple containing
|
||||
impl SerializablePusPacket for PusTmCreator<'_> {
|
||||
fn len_packed(&self) -> usize {
|
||||
PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA
|
||||
+ self.sec_header.timestamp.len()
|
||||
+ self.source_data.len()
|
||||
}
|
||||
/// Write the raw PUS byte representation to a provided buffer.
|
||||
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
|
||||
let mut curr_idx = 0;
|
||||
let total_size = self.len_packed();
|
||||
if total_size > slice.len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: slice.len(),
|
||||
expected: total_size,
|
||||
}
|
||||
.into());
|
||||
}
|
||||
self.sp_header
|
||||
.write_to_be_bytes(&mut slice[0..CCSDS_HEADER_LEN])?;
|
||||
curr_idx += CCSDS_HEADER_LEN;
|
||||
let sec_header_len = size_of::<zc::PusTmSecHeaderWithoutTimestamp>();
|
||||
let sec_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
|
||||
sec_header
|
||||
.write_to_bytes(&mut slice[curr_idx..curr_idx + sec_header_len])
|
||||
.ok_or(ByteConversionError::ZeroCopyToError)?;
|
||||
curr_idx += sec_header_len;
|
||||
slice[curr_idx..curr_idx + self.sec_header.timestamp.len()]
|
||||
.copy_from_slice(self.sec_header.timestamp);
|
||||
curr_idx += self.sec_header.timestamp.len();
|
||||
slice[curr_idx..curr_idx + self.source_data.len()].copy_from_slice(self.source_data);
|
||||
curr_idx += self.source_data.len();
|
||||
let mut digest = CRC_CCITT_FALSE.digest();
|
||||
digest.update(&slice[0..curr_idx]);
|
||||
slice[curr_idx..curr_idx + 2].copy_from_slice(&digest.finalize().to_be_bytes());
|
||||
curr_idx += 2;
|
||||
Ok(curr_idx)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for PusTmCreator<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.sp_header == other.sp_header
|
||||
&& self.sec_header == other.sec_header
|
||||
&& self.source_data == other.source_data
|
||||
}
|
||||
}
|
||||
|
||||
impl CcsdsPacket for PusTmCreator<'_> {
|
||||
ccsds_impl!();
|
||||
}
|
||||
|
||||
impl PusPacket for PusTmCreator<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
});
|
||||
|
||||
fn user_data(&self) -> &[u8] {
|
||||
self.source_data
|
||||
}
|
||||
|
||||
fn crc16(&self) -> Option<u16> {
|
||||
Some(self.calc_own_crc16())
|
||||
}
|
||||
}
|
||||
|
||||
impl GenericPusTmSecondaryHeader for PusTmCreator<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
fn dest_id(&self) -> u16;
|
||||
fn msg_counter(&self) -> u16;
|
||||
fn sc_time_ref_status(&self) -> u8;
|
||||
});
|
||||
}
|
||||
|
||||
impl IsPusTelemetry for PusTmCreator<'_> {}
|
||||
|
||||
/// This class models the PUS C telemetry packet. It is the primary data structure to read
|
||||
/// a telemetry packet from raw bytes.
|
||||
///
|
||||
/// This class also derives the [serde::Serialize] and [serde::Deserialize] trait if the [serde]
|
||||
/// feature is used which allows to send around TM packets in a raw byte format using a serde
|
||||
/// provider like [postcard](https://docs.rs/postcard/latest/postcard/).
|
||||
///
|
||||
/// There is no spare bytes support yet.
|
||||
///
|
||||
/// # Lifetimes
|
||||
///
|
||||
/// * `'raw_data` - Lifetime of the raw slice this class is constructed from.
|
||||
#[derive(Eq, Debug, Copy, Clone)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct PusTmReader<'raw_data> {
|
||||
pub sp_header: SpHeader,
|
||||
pub sec_header: PusTmSecondaryHeader<'raw_data>,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
raw_data: &'raw_data [u8],
|
||||
source_data: &'raw_data [u8],
|
||||
crc16: u16,
|
||||
}
|
||||
|
||||
impl<'raw_data> PusTmReader<'raw_data> {
|
||||
/// Create a [PusTmReader] instance from a raw slice. On success, it returns a tuple containing
|
||||
/// the instance and the found byte length of the packet. The timestamp length needs to be
|
||||
/// known beforehand.
|
||||
pub fn from_bytes(
|
||||
slice: &'raw_data [u8],
|
||||
timestamp_len: usize,
|
||||
) -> Result<(Self, usize), PusError> {
|
||||
pub fn new(slice: &'raw_data [u8], timestamp_len: usize) -> Result<(Self, usize), PusError> {
|
||||
let raw_data_len = slice.len();
|
||||
if raw_data_len < PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA {
|
||||
return Err(PusError::RawDataTooShort(raw_data_len));
|
||||
@ -370,38 +774,96 @@ impl<'raw_data> PusTm<'raw_data> {
|
||||
)
|
||||
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||
current_idx += PUC_TM_MIN_SEC_HEADER_LEN;
|
||||
let mut timestamp = None;
|
||||
if timestamp_len > 0 {
|
||||
timestamp = Some(&slice[current_idx..current_idx + timestamp_len]);
|
||||
}
|
||||
let zc_sec_header_wrapper = zc::PusTmSecHeader {
|
||||
zc_header: sec_header_zc,
|
||||
timestamp,
|
||||
timestamp: &slice[current_idx..current_idx + timestamp_len],
|
||||
};
|
||||
current_idx += timestamp_len;
|
||||
let raw_data = &slice[0..total_len];
|
||||
let pus_tm = PusTm {
|
||||
let pus_tm = Self {
|
||||
sp_header,
|
||||
sec_header: PusTmSecondaryHeader::try_from(zc_sec_header_wrapper).unwrap(),
|
||||
raw_data: Some(&slice[0..total_len]),
|
||||
raw_data: &slice[0..total_len],
|
||||
source_data: user_data_from_raw(current_idx, total_len, raw_data_len, slice)?,
|
||||
calc_crc_on_serialization: false,
|
||||
crc16: Some(crc_from_raw_data(raw_data)?),
|
||||
crc16: crc_from_raw_data(raw_data)?,
|
||||
};
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error(
|
||||
raw_data,
|
||||
pus_tm.crc16.expect("CRC16 invalid"),
|
||||
)?;
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error(raw_data, pus_tm.crc16)?;
|
||||
Ok((pus_tm, total_len))
|
||||
}
|
||||
|
||||
/// If [Self] was constructed [Self::from_bytes], this function will return the slice it was
|
||||
/// constructed from. Otherwise, [None] will be returned.
|
||||
pub fn raw_bytes(&self) -> Option<&'raw_data [u8]> {
|
||||
pub fn len_packed(&self) -> usize {
|
||||
self.sp_header.total_len()
|
||||
}
|
||||
|
||||
pub fn source_data(&self) -> &[u8] {
|
||||
self.user_data()
|
||||
}
|
||||
|
||||
pub fn timestamp(&self) -> &[u8] {
|
||||
self.sec_header.timestamp
|
||||
}
|
||||
|
||||
/// This function will return the slice [Self] was constructed from.
|
||||
pub fn raw_data(&self) -> &[u8] {
|
||||
self.raw_data
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for PusTmReader<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.raw_data == other.raw_data
|
||||
}
|
||||
}
|
||||
|
||||
impl CcsdsPacket for PusTmReader<'_> {
|
||||
ccsds_impl!();
|
||||
}
|
||||
|
||||
impl PusPacket for PusTmReader<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
});
|
||||
|
||||
fn user_data(&self) -> &[u8] {
|
||||
self.source_data
|
||||
}
|
||||
|
||||
fn crc16(&self) -> Option<u16> {
|
||||
Some(self.crc16)
|
||||
}
|
||||
}
|
||||
|
||||
impl GenericPusTmSecondaryHeader for PusTmReader<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
fn dest_id(&self) -> u16;
|
||||
fn msg_counter(&self) -> u16;
|
||||
fn sc_time_ref_status(&self) -> u8;
|
||||
});
|
||||
}
|
||||
|
||||
impl IsPusTelemetry for PusTmReader<'_> {}
|
||||
|
||||
impl PartialEq<PusTmCreator<'_>> for PusTmReader<'_> {
|
||||
fn eq(&self, other: &PusTmCreator<'_>) -> bool {
|
||||
self.sp_header == other.sp_header
|
||||
&& self.sec_header == other.sec_header
|
||||
&& self.source_data == other.source_data
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq<PusTmReader<'_>> for PusTmCreator<'_> {
|
||||
fn eq(&self, other: &PusTmReader<'_>) -> bool {
|
||||
self.sp_header == other.sp_header
|
||||
&& self.sec_header == other.sec_header
|
||||
&& self.source_data == other.source_data
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a helper class to update certain fields in a raw PUS telemetry packet directly in place.
|
||||
/// This can be more efficient than creating a full [PusTm], modifying the fields and then writing
|
||||
/// it back to another buffer.
|
||||
@ -479,117 +941,22 @@ impl<'raw> PusTmZeroCopyWriter<'raw> {
|
||||
}
|
||||
}
|
||||
|
||||
impl SerializablePusPacket for PusTm<'_> {
|
||||
fn len_packed(&self) -> usize {
|
||||
let mut length = PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA;
|
||||
if let Some(timestamp) = self.sec_header.timestamp {
|
||||
length += timestamp.len();
|
||||
}
|
||||
if let Some(src_data) = self.source_data {
|
||||
length += src_data.len();
|
||||
}
|
||||
length
|
||||
}
|
||||
/// Write the raw PUS byte representation to a provided buffer.
|
||||
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
|
||||
let mut curr_idx = 0;
|
||||
let total_size = self.len_packed();
|
||||
if total_size > slice.len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
found: slice.len(),
|
||||
expected: total_size,
|
||||
})
|
||||
.into());
|
||||
}
|
||||
self.sp_header
|
||||
.write_to_be_bytes(&mut slice[0..CCSDS_HEADER_LEN])?;
|
||||
curr_idx += CCSDS_HEADER_LEN;
|
||||
let sec_header_len = size_of::<zc::PusTmSecHeaderWithoutTimestamp>();
|
||||
let sec_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
|
||||
sec_header
|
||||
.write_to_bytes(&mut slice[curr_idx..curr_idx + sec_header_len])
|
||||
.ok_or(ByteConversionError::ZeroCopyToError)?;
|
||||
curr_idx += sec_header_len;
|
||||
if let Some(timestamp) = self.sec_header.timestamp {
|
||||
let timestamp_len = timestamp.len();
|
||||
slice[curr_idx..curr_idx + timestamp_len].copy_from_slice(timestamp);
|
||||
curr_idx += timestamp_len;
|
||||
}
|
||||
if let Some(src_data) = self.source_data {
|
||||
slice[curr_idx..curr_idx + src_data.len()].copy_from_slice(src_data);
|
||||
curr_idx += src_data.len();
|
||||
}
|
||||
let crc16 = crc_procedure(
|
||||
self.calc_crc_on_serialization,
|
||||
&self.crc16,
|
||||
0,
|
||||
curr_idx,
|
||||
slice,
|
||||
)?;
|
||||
slice[curr_idx..curr_idx + 2].copy_from_slice(crc16.to_be_bytes().as_slice());
|
||||
curr_idx += 2;
|
||||
Ok(curr_idx)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for PusTm<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.sp_header == other.sp_header
|
||||
&& self.sec_header == other.sec_header
|
||||
&& self.source_data == other.source_data
|
||||
}
|
||||
}
|
||||
|
||||
//noinspection RsTraitImplementation
|
||||
impl CcsdsPacket for PusTm<'_> {
|
||||
ccsds_impl!();
|
||||
}
|
||||
|
||||
//noinspection RsTraitImplementation
|
||||
impl PusPacket for PusTm<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
});
|
||||
|
||||
fn user_data(&self) -> Option<&[u8]> {
|
||||
self.source_data
|
||||
}
|
||||
|
||||
fn crc16(&self) -> Option<u16> {
|
||||
self.crc16
|
||||
}
|
||||
}
|
||||
|
||||
//noinspection RsTraitImplementation
|
||||
impl GenericPusTmSecondaryHeader for PusTm<'_> {
|
||||
delegate!(to self.sec_header {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
fn service(&self) -> u8;
|
||||
fn subservice(&self) -> u8;
|
||||
fn dest_id(&self) -> u16;
|
||||
fn msg_counter(&self) -> u16;
|
||||
fn sc_time_ref_status(&self) -> u8;
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ecss::PusVersion::PusC;
|
||||
use crate::SpHeader;
|
||||
|
||||
fn base_ping_reply_full_ctor(timestamp: &[u8]) -> PusTm {
|
||||
fn base_ping_reply_full_ctor(timestamp: &[u8]) -> PusTmCreator {
|
||||
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, ×tamp);
|
||||
PusTm::new(&mut sph, tm_header, None, true)
|
||||
PusTmCreator::new(&mut sph, tm_header, None, true)
|
||||
}
|
||||
|
||||
fn base_hk_reply<'a>(timestamp: &'a [u8], src_data: &'a [u8]) -> PusTm<'a> {
|
||||
fn base_hk_reply<'a>(timestamp: &'a [u8], src_data: &'a [u8]) -> PusTmCreator<'a> {
|
||||
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
|
||||
let tc_header = PusTmSecondaryHeader::new_simple(3, 5, ×tamp);
|
||||
PusTm::new(&mut sph, tc_header, Some(src_data), true)
|
||||
PusTmCreator::new(&mut sph, tc_header, Some(src_data), true)
|
||||
}
|
||||
|
||||
fn dummy_timestamp() -> &'static [u8] {
|
||||
@ -652,22 +1019,19 @@ mod tests {
|
||||
.write_to_bytes(&mut buf)
|
||||
.expect("Serialization failed");
|
||||
assert_eq!(ser_len, 22);
|
||||
let (tm_deserialized, size) = PusTm::from_bytes(&buf, 7).expect("Deserialization failed");
|
||||
let (tm_deserialized, size) = PusTmReader::new(&buf, 7).expect("Deserialization failed");
|
||||
assert_eq!(ser_len, size);
|
||||
verify_ping_reply(&tm_deserialized, false, 22, dummy_timestamp());
|
||||
verify_ping_reply_with_reader(&tm_deserialized, false, 22, dummy_timestamp());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_manual_field_update() {
|
||||
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
|
||||
let tc_header = PusTmSecondaryHeader::new_simple(17, 2, dummy_timestamp());
|
||||
let mut tm = PusTm::new(&mut sph, tc_header, None, false);
|
||||
let mut tm = PusTmCreator::new(&mut sph, tc_header, None, false);
|
||||
tm.calc_crc_on_serialization = false;
|
||||
assert_eq!(tm.data_len(), 0x00);
|
||||
let mut buf: [u8; 32] = [0; 32];
|
||||
let res = tm.write_to_bytes(&mut buf);
|
||||
assert!(res.is_err());
|
||||
assert!(matches!(res.unwrap_err(), PusError::CrcCalculationMissing));
|
||||
tm.update_ccsds_data_len();
|
||||
assert_eq!(tm.data_len(), 15);
|
||||
tm.calc_own_crc16();
|
||||
@ -686,12 +1050,12 @@ mod tests {
|
||||
let res = pus_tm.write_to_bytes(&mut buf);
|
||||
assert!(res.is_err());
|
||||
let error = res.unwrap_err();
|
||||
assert!(matches!(error, PusError::ByteConversionError { .. }));
|
||||
assert!(matches!(error, PusError::ByteConversion { .. }));
|
||||
match error {
|
||||
PusError::ByteConversionError(err) => match err {
|
||||
ByteConversionError::ToSliceTooSmall(size_missmatch) => {
|
||||
assert_eq!(size_missmatch.expected, 22);
|
||||
assert_eq!(size_missmatch.found, 16);
|
||||
PusError::ByteConversion(err) => match err {
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(expected, 22);
|
||||
assert_eq!(found, 16);
|
||||
}
|
||||
_ => panic!("Invalid PUS error {:?}", err),
|
||||
},
|
||||
@ -755,19 +1119,38 @@ mod tests {
|
||||
}
|
||||
|
||||
fn verify_ping_reply(
|
||||
tm: &PusTm,
|
||||
tm: &PusTmCreator,
|
||||
has_user_data: bool,
|
||||
exp_full_len: usize,
|
||||
exp_timestamp: &[u8],
|
||||
) {
|
||||
assert_eq!(tm.len_packed(), exp_full_len);
|
||||
assert_eq!(tm.timestamp(), exp_timestamp);
|
||||
verify_ping_reply_generic(tm, has_user_data, exp_full_len);
|
||||
}
|
||||
|
||||
fn verify_ping_reply_with_reader(
|
||||
tm: &PusTmReader,
|
||||
has_user_data: bool,
|
||||
exp_full_len: usize,
|
||||
exp_timestamp: &[u8],
|
||||
) {
|
||||
assert_eq!(tm.len_packed(), exp_full_len);
|
||||
assert_eq!(tm.timestamp(), exp_timestamp);
|
||||
verify_ping_reply_generic(tm, has_user_data, exp_full_len);
|
||||
}
|
||||
|
||||
fn verify_ping_reply_generic(
|
||||
tm: &(impl CcsdsPacket + GenericPusTmSecondaryHeader + PusPacket),
|
||||
has_user_data: bool,
|
||||
exp_full_len: usize,
|
||||
) {
|
||||
assert!(tm.is_tm());
|
||||
assert_eq!(PusPacket::service(tm), 17);
|
||||
assert_eq!(PusPacket::subservice(tm), 2);
|
||||
assert!(tm.sec_header_flag());
|
||||
assert_eq!(tm.len_packed(), exp_full_len);
|
||||
assert_eq!(tm.timestamp().unwrap(), exp_timestamp);
|
||||
if has_user_data {
|
||||
assert!(!tm.user_data().is_none());
|
||||
assert!(!tm.user_data().is_empty());
|
||||
}
|
||||
assert_eq!(PusPacket::pus_version(tm), PusC);
|
||||
assert_eq!(tm.apid(), 0x123);
|
||||
@ -792,7 +1175,7 @@ mod tests {
|
||||
let pus_tm = base_ping_reply_full_ctor(timestamp);
|
||||
let mut buf = [0; 32];
|
||||
pus_tm.write_to_bytes(&mut buf).unwrap();
|
||||
assert_eq!(pus_tm, PusTm::from_bytes(&buf, timestamp.len()).unwrap().0);
|
||||
assert_eq!(pus_tm, PusTmReader::new(&buf, timestamp.len()).unwrap().0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -811,7 +1194,7 @@ mod tests {
|
||||
writer.finish();
|
||||
// This performs all necessary checks, including the CRC check.
|
||||
let (tm_read_back, tm_size_read_back) =
|
||||
PusTm::from_bytes(&buf, 7).expect("Re-creating PUS TM failed");
|
||||
PusTmReader::new(&buf, 7).expect("Re-creating PUS TM failed");
|
||||
assert_eq!(tm_size_read_back, tm_size);
|
||||
assert_eq!(tm_read_back.msg_counter(), 100);
|
||||
assert_eq!(tm_read_back.dest_id(), 55);
|
43
src/lib.rs
43
src/lib.rs
@ -65,8 +65,7 @@ use crate::ecss::CCSDS_HEADER_LEN;
|
||||
use core::fmt::{Debug, Display, Formatter};
|
||||
use crc::{Crc, CRC_16_IBM_3740};
|
||||
use delegate::delegate;
|
||||
#[cfg(not(feature = "std"))]
|
||||
use num_traits::Unsigned;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::error::Error;
|
||||
|
||||
@ -75,9 +74,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
pub mod cfdp;
|
||||
pub mod ecss;
|
||||
pub mod tc;
|
||||
pub mod time;
|
||||
pub mod tm;
|
||||
pub mod util;
|
||||
|
||||
mod private {
|
||||
@ -90,20 +87,20 @@ pub const CRC_CCITT_FALSE: Crc<u16> = Crc::<u16>::new(&CRC_16_IBM_3740);
|
||||
pub const MAX_APID: u16 = 2u16.pow(11) - 1;
|
||||
pub const MAX_SEQ_COUNT: u16 = 2u16.pow(14) - 1;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct SizeMissmatch {
|
||||
pub found: usize,
|
||||
pub expected: usize,
|
||||
}
|
||||
|
||||
/// Generic error type when converting to and from raw byte slices.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum ByteConversionError {
|
||||
/// The passed slice is too small. Returns the passed slice length and expected minimum size
|
||||
ToSliceTooSmall(SizeMissmatch),
|
||||
ToSliceTooSmall {
|
||||
found: usize,
|
||||
expected: usize,
|
||||
},
|
||||
/// The provider buffer is too small. Returns the passed slice length and expected minimum size
|
||||
FromSliceTooSmall(SizeMissmatch),
|
||||
FromSliceTooSmall {
|
||||
found: usize,
|
||||
expected: usize,
|
||||
},
|
||||
/// The [zerocopy] library failed to write to bytes
|
||||
ZeroCopyToError,
|
||||
ZeroCopyFromError,
|
||||
@ -112,18 +109,18 @@ pub enum ByteConversionError {
|
||||
impl Display for ByteConversionError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
write!(
|
||||
f,
|
||||
"target slice with size {} is too small, expected size of at least {}",
|
||||
missmatch.found, missmatch.expected
|
||||
found, expected
|
||||
)
|
||||
}
|
||||
ByteConversionError::FromSliceTooSmall(missmatch) => {
|
||||
ByteConversionError::FromSliceTooSmall { found, expected } => {
|
||||
write!(
|
||||
f,
|
||||
"source slice with size {} too small, expected at least {} bytes",
|
||||
missmatch.found, missmatch.expected
|
||||
found, expected
|
||||
)
|
||||
}
|
||||
ByteConversionError::ZeroCopyToError => {
|
||||
@ -567,10 +564,10 @@ impl SpHeader {
|
||||
/// CCSDS header.
|
||||
pub fn from_be_bytes(buf: &[u8]) -> Result<(Self, &[u8]), ByteConversionError> {
|
||||
if buf.len() < CCSDS_HEADER_LEN {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: CCSDS_HEADER_LEN,
|
||||
}));
|
||||
});
|
||||
}
|
||||
let zc_header = zc::SpHeader::from_bytes(&buf[0..CCSDS_HEADER_LEN])
|
||||
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||
@ -584,10 +581,10 @@ impl SpHeader {
|
||||
buf: &'a mut [u8],
|
||||
) -> Result<&'a mut [u8], ByteConversionError> {
|
||||
if buf.len() < CCSDS_HEADER_LEN {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: CCSDS_HEADER_LEN,
|
||||
}));
|
||||
});
|
||||
}
|
||||
let zc_header: zc::SpHeader = zc::SpHeader::from(*self);
|
||||
zc_header
|
||||
@ -644,9 +641,9 @@ sph_from_other!(SpHeader, crate::zc::SpHeader);
|
||||
pub mod zc {
|
||||
use crate::{CcsdsPacket, CcsdsPrimaryHeader, PacketId, PacketSequenceCtrl, VERSION_MASK};
|
||||
use zerocopy::byteorder::NetworkEndian;
|
||||
use zerocopy::{AsBytes, FromBytes, Unaligned, U16};
|
||||
use zerocopy::{AsBytes, FromBytes, FromZeroes, Unaligned, U16};
|
||||
|
||||
#[derive(FromBytes, AsBytes, Unaligned, Debug)]
|
||||
#[derive(FromBytes, FromZeroes, AsBytes, Unaligned, Debug)]
|
||||
#[repr(C)]
|
||||
pub struct SpHeader {
|
||||
version_packet_id: U16<NetworkEndian>,
|
||||
|
@ -428,14 +428,17 @@ pub fn get_dyn_time_provider_from_bytes(
|
||||
) -> Result<Box<dyn DynCdsTimeProvider>, TimestampError> {
|
||||
let time_code = ccsds_time_code_from_p_field(buf[0]);
|
||||
if let Err(e) = time_code {
|
||||
return Err(TimestampError::InvalidTimeCode(CcsdsTimeCodes::Cds, e));
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::Cds,
|
||||
found: e,
|
||||
});
|
||||
}
|
||||
let time_code = time_code.unwrap();
|
||||
if time_code != CcsdsTimeCodes::Cds {
|
||||
return Err(TimestampError::InvalidTimeCode(
|
||||
CcsdsTimeCodes::Cds,
|
||||
time_code as u8,
|
||||
));
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::Cds,
|
||||
found: time_code as u8,
|
||||
});
|
||||
}
|
||||
if length_of_day_segment_from_pfield(buf[0]) == LengthOfDaySegment::Short16Bits {
|
||||
Ok(Box::new(TimeProvider::from_bytes_with_u16_days(buf)?))
|
||||
@ -511,11 +514,11 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
days_len: LengthOfDaySegment,
|
||||
) -> Result<SubmillisPrecision, TimestampError> {
|
||||
if buf.len() < MIN_CDS_FIELD_LEN {
|
||||
return Err(TimestampError::ByteConversionError(
|
||||
ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::FromSliceTooSmall {
|
||||
expected: MIN_CDS_FIELD_LEN,
|
||||
found: buf.len(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
let pfield = buf[0];
|
||||
@ -523,17 +526,17 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
Ok(cds_type) => match cds_type {
|
||||
CcsdsTimeCodes::Cds => (),
|
||||
_ => {
|
||||
return Err(TimestampError::InvalidTimeCode(
|
||||
CcsdsTimeCodes::Cds,
|
||||
cds_type as u8,
|
||||
))
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::Cds,
|
||||
found: cds_type as u8,
|
||||
})
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
return Err(TimestampError::InvalidTimeCode(
|
||||
CcsdsTimeCodes::Cds,
|
||||
pfield >> 4 & 0b111,
|
||||
))
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::Cds,
|
||||
found: pfield >> 4 & 0b111,
|
||||
});
|
||||
}
|
||||
};
|
||||
if ((pfield >> 3) & 0b1) == 1 {
|
||||
@ -545,11 +548,11 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
}
|
||||
let stamp_len = Self::calc_stamp_len(pfield);
|
||||
if buf.len() < stamp_len {
|
||||
return Err(TimestampError::ByteConversionError(
|
||||
ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::FromSliceTooSmall {
|
||||
expected: stamp_len,
|
||||
found: buf.len(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
Ok(precision_from_pfield(pfield))
|
||||
@ -602,11 +605,11 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
|
||||
fn length_check(&self, buf: &[u8], len_as_bytes: usize) -> Result<(), TimestampError> {
|
||||
if buf.len() < len_as_bytes {
|
||||
return Err(TimestampError::ByteConversionError(
|
||||
ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::ToSliceTooSmall {
|
||||
expected: len_as_bytes,
|
||||
found: buf.len(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
@ -671,21 +674,21 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
fn from_now_generic(days_len: LengthOfDaySegment) -> Result<Self, StdTimestampError> {
|
||||
let conversion_from_now = ConversionFromNow::new()?;
|
||||
Self::generic_from_conversion(days_len, conversion_from_now)
|
||||
.map_err(StdTimestampError::TimestampError)
|
||||
.map_err(StdTimestampError::Timestamp)
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
fn from_now_generic_us_prec(days_len: LengthOfDaySegment) -> Result<Self, StdTimestampError> {
|
||||
let conversion_from_now = ConversionFromNow::new_with_submillis_us_prec()?;
|
||||
Self::generic_from_conversion(days_len, conversion_from_now)
|
||||
.map_err(StdTimestampError::TimestampError)
|
||||
.map_err(StdTimestampError::Timestamp)
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
fn from_now_generic_ps_prec(days_len: LengthOfDaySegment) -> Result<Self, StdTimestampError> {
|
||||
let conversion_from_now = ConversionFromNow::new_with_submillis_ps_prec()?;
|
||||
Self::generic_from_conversion(days_len, conversion_from_now)
|
||||
.map_err(StdTimestampError::TimestampError)
|
||||
.map_err(StdTimestampError::Timestamp)
|
||||
}
|
||||
|
||||
fn generic_from_conversion<C: CdsConverter>(
|
||||
@ -694,7 +697,7 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
) -> Result<Self, TimestampError> {
|
||||
let ccsds_days: ProvidesDaysLen::FieldType =
|
||||
converter.ccsds_days_as_u32().try_into().map_err(|_| {
|
||||
TimestampError::CdsError(CdsError::InvalidCcsdsDays(
|
||||
TimestampError::Cds(CdsError::InvalidCcsdsDays(
|
||||
converter.ccsds_days_as_u32().into(),
|
||||
))
|
||||
})?;
|
||||
@ -750,7 +753,7 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
.ccsds_days
|
||||
.try_into()
|
||||
.map_err(|_| {
|
||||
StdTimestampError::TimestampError(
|
||||
StdTimestampError::Timestamp(
|
||||
CdsError::InvalidCcsdsDays(
|
||||
conversion_from_now.unix_conversion.ccsds_days as i64,
|
||||
)
|
||||
@ -788,7 +791,7 @@ impl TimeProvider<DaysLen24Bits> {
|
||||
/// ## Errors
|
||||
///
|
||||
/// This function will return [TimestampError::DateBeforeCcsdsEpoch] or
|
||||
/// [TimestampError::CdsError] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00)
|
||||
/// [TimestampError::Cds] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00)
|
||||
/// or the CCSDS days value exceeds the allowed bit width (24 bits).
|
||||
pub fn from_dt_with_u24_days(dt: &DateTime<Utc>) -> Result<Self, TimestampError> {
|
||||
Self::from_dt_generic(dt, LengthOfDaySegment::Long24Bits)
|
||||
@ -799,7 +802,7 @@ impl TimeProvider<DaysLen24Bits> {
|
||||
/// ## Errors
|
||||
///
|
||||
/// This function will return [TimestampError::DateBeforeCcsdsEpoch] or
|
||||
/// [TimestampError::CdsError] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00)
|
||||
/// [TimestampError::Cds] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00)
|
||||
/// or the CCSDS days value exceeds the allowed bit width (24 bits).
|
||||
pub fn from_unix_secs_with_u24_days(
|
||||
unix_stamp: &UnixTimestamp,
|
||||
@ -864,7 +867,7 @@ impl TimeProvider<DaysLen16Bits> {
|
||||
/// Create a provider from a [`DateTime<Utc>`] struct.
|
||||
///
|
||||
/// This function will return a [TimestampError::DateBeforeCcsdsEpoch] or a
|
||||
/// [TimestampError::CdsError] if the time is before the CCSDS epoch (01-01-1958 00:00:00) or
|
||||
/// [TimestampError::Cds] if the time is before the CCSDS epoch (01-01-1958 00:00:00) or
|
||||
/// the CCSDS days value exceeds the allowed bit width (16 bits).
|
||||
pub fn from_dt_with_u16_days(dt: &DateTime<Utc>) -> Result<Self, TimestampError> {
|
||||
Self::from_dt_generic(dt, LengthOfDaySegment::Short16Bits)
|
||||
@ -882,7 +885,7 @@ impl TimeProvider<DaysLen16Bits> {
|
||||
/// ## Errors
|
||||
///
|
||||
/// This function will return [TimestampError::DateBeforeCcsdsEpoch] or
|
||||
/// [TimestampError::CdsError] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00)
|
||||
/// [TimestampError::Cds] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00)
|
||||
/// or the CCSDS days value exceeds the allowed bit width (24 bits).
|
||||
pub fn from_unix_secs_with_u16_days(
|
||||
unix_stamp: &UnixTimestamp,
|
||||
@ -1302,7 +1305,7 @@ impl TryFrom<TimeProvider<DaysLen24Bits>> for TimeProvider<DaysLen16Bits> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::time::TimestampError::{ByteConversionError, InvalidTimeCode};
|
||||
use crate::time::TimestampError::{ByteConversion, InvalidTimeCode};
|
||||
use crate::ByteConversionError::{FromSliceTooSmall, ToSliceTooSmall};
|
||||
use chrono::{Datelike, NaiveDate, Timelike};
|
||||
#[cfg(feature = "serde")]
|
||||
@ -1400,8 +1403,7 @@ mod tests {
|
||||
let faulty_ctor = TimeProvider::<DaysLen16Bits>::from_bytes(&buf);
|
||||
assert!(faulty_ctor.is_err());
|
||||
let error = faulty_ctor.unwrap_err();
|
||||
if let TimestampError::CdsError(CdsError::InvalidCtorForDaysOfLenInPreamble(len_of_day)) =
|
||||
error
|
||||
if let TimestampError::Cds(CdsError::InvalidCtorForDaysOfLenInPreamble(len_of_day)) = error
|
||||
{
|
||||
assert_eq!(len_of_day, LengthOfDaySegment::Long24Bits);
|
||||
} else {
|
||||
@ -1446,9 +1448,9 @@ mod tests {
|
||||
let res = time_stamper.write_to_bytes(&mut buf[0..i]);
|
||||
assert!(res.is_err());
|
||||
match res.unwrap_err() {
|
||||
ByteConversionError(ToSliceTooSmall(missmatch)) => {
|
||||
assert_eq!(missmatch.found, i);
|
||||
assert_eq!(missmatch.expected, 7);
|
||||
ByteConversion(ToSliceTooSmall { found, expected }) => {
|
||||
assert_eq!(found, i);
|
||||
assert_eq!(expected, 7);
|
||||
}
|
||||
_ => panic!(
|
||||
"{}",
|
||||
@ -1466,10 +1468,10 @@ mod tests {
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
ByteConversionError(e) => match e {
|
||||
FromSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.found, i);
|
||||
assert_eq!(missmatch.expected, 7);
|
||||
ByteConversion(e) => match e {
|
||||
FromSliceTooSmall { found, expected } => {
|
||||
assert_eq!(found, i);
|
||||
assert_eq!(expected, 7);
|
||||
}
|
||||
_ => panic!("{}", format!("Invalid error {:?} detected", e)),
|
||||
},
|
||||
@ -1491,9 +1493,9 @@ mod tests {
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
InvalidTimeCode(code, raw) => {
|
||||
assert_eq!(code, CcsdsTimeCodes::Cds);
|
||||
assert_eq!(raw, 0);
|
||||
InvalidTimeCode { expected, found } => {
|
||||
assert_eq!(expected, CcsdsTimeCodes::Cds);
|
||||
assert_eq!(found, 0);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@ -1762,7 +1764,7 @@ mod tests {
|
||||
fn generic_dt_case_1_us_prec(subsec_millis: u32) -> DateTime<Utc> {
|
||||
// 250 ms + 500 us
|
||||
let subsec_micros = subsec_millis * 1000 + 500;
|
||||
let naivedatetime_utc = NaiveDate::from_ymd_opt(2023, 01, 14)
|
||||
let naivedatetime_utc = NaiveDate::from_ymd_opt(2023, 1, 14)
|
||||
.unwrap()
|
||||
.and_hms_micro_opt(16, 49, 30, subsec_micros)
|
||||
.unwrap();
|
||||
@ -1813,7 +1815,7 @@ mod tests {
|
||||
// 250 ms + 500 us
|
||||
let subsec_nanos = subsec_millis * 1000 * 1000 + 500 * 1000;
|
||||
let submilli_nanos = subsec_nanos % 10_u32.pow(6);
|
||||
let naivedatetime_utc = NaiveDate::from_ymd_opt(2023, 01, 14)
|
||||
let naivedatetime_utc = NaiveDate::from_ymd_opt(2023, 1, 14)
|
||||
.unwrap()
|
||||
.and_hms_nano_opt(16, 49, 30, subsec_nanos)
|
||||
.unwrap();
|
||||
@ -1943,7 +1945,7 @@ mod tests {
|
||||
panic!("creation should not succeed")
|
||||
}
|
||||
Err(e) => {
|
||||
if let TimestampError::CdsError(CdsError::InvalidCcsdsDays(days)) = e {
|
||||
if let TimestampError::Cds(CdsError::InvalidCcsdsDays(days)) = e {
|
||||
assert_eq!(
|
||||
days,
|
||||
unix_to_ccsds_days(invalid_unix_secs / SECONDS_PER_DAY as i64)
|
||||
|
@ -244,7 +244,7 @@ impl TimeProviderCcsdsEpoch {
|
||||
let fractions =
|
||||
fractional_part_from_subsec_ns(fraction_resolution, now.subsec_nanos() as u64);
|
||||
Self::new_with_fractions(ccsds_epoch as u32, fractions.unwrap())
|
||||
.map_err(|e| StdTimestampError::TimestampError(e.into()))
|
||||
.map_err(|e| StdTimestampError::Timestamp(e.into()))
|
||||
}
|
||||
|
||||
/// Updates the current time stamp from the current time. The fractional field width remains
|
||||
@ -453,37 +453,37 @@ impl TimeReader for TimeProviderCcsdsEpoch {
|
||||
Self: Sized,
|
||||
{
|
||||
if buf.len() < MIN_CUC_LEN {
|
||||
return Err(TimestampError::ByteConversionError(
|
||||
ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::FromSliceTooSmall {
|
||||
expected: MIN_CUC_LEN,
|
||||
found: buf.len(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
match ccsds_time_code_from_p_field(buf[0]) {
|
||||
Ok(code) => {
|
||||
if code != CcsdsTimeCodes::CucCcsdsEpoch {
|
||||
return Err(TimestampError::InvalidTimeCode(
|
||||
CcsdsTimeCodes::CucCcsdsEpoch,
|
||||
code as u8,
|
||||
));
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::CucCcsdsEpoch,
|
||||
found: code as u8,
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(raw) => {
|
||||
return Err(TimestampError::InvalidTimeCode(
|
||||
CcsdsTimeCodes::CucCcsdsEpoch,
|
||||
raw,
|
||||
))
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::CucCcsdsEpoch,
|
||||
found: raw,
|
||||
});
|
||||
}
|
||||
}
|
||||
let (cntr_len, fractions_len, total_len) =
|
||||
Self::len_components_and_total_from_pfield(buf[0]);
|
||||
if buf.len() < total_len {
|
||||
return Err(TimestampError::ByteConversionError(
|
||||
ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::FromSliceTooSmall {
|
||||
expected: total_len,
|
||||
found: buf.len(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
let mut current_idx = 1;
|
||||
@ -535,11 +535,11 @@ impl TimeWriter for TimeProviderCcsdsEpoch {
|
||||
fn write_to_bytes(&self, bytes: &mut [u8]) -> Result<usize, TimestampError> {
|
||||
// Cross check the sizes of the counters against byte widths in the ctor
|
||||
if bytes.len() < self.len_as_bytes() {
|
||||
return Err(TimestampError::ByteConversionError(
|
||||
ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::ToSliceTooSmall {
|
||||
found: bytes.len(),
|
||||
expected: self.len_as_bytes(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
bytes[0] = self.pfield;
|
||||
@ -797,11 +797,13 @@ mod tests {
|
||||
let res = TimeProviderCcsdsEpoch::from_bytes(&buf[0..i]);
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
if let TimestampError::ByteConversionError(ByteConversionError::FromSliceTooSmall(e)) =
|
||||
err
|
||||
if let TimestampError::ByteConversion(ByteConversionError::FromSliceTooSmall {
|
||||
found,
|
||||
expected,
|
||||
}) = err
|
||||
{
|
||||
assert_eq!(e.found, i);
|
||||
assert_eq!(e.expected, 2);
|
||||
assert_eq!(found, i);
|
||||
assert_eq!(expected, 2);
|
||||
}
|
||||
}
|
||||
let large_stamp = TimeProviderCcsdsEpoch::new_with_fine_fractions(22, 300).unwrap();
|
||||
@ -810,11 +812,13 @@ mod tests {
|
||||
let res = TimeProviderCcsdsEpoch::from_bytes(&buf[0..i]);
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
if let TimestampError::ByteConversionError(ByteConversionError::FromSliceTooSmall(e)) =
|
||||
err
|
||||
if let TimestampError::ByteConversion(ByteConversionError::FromSliceTooSmall {
|
||||
found,
|
||||
expected,
|
||||
}) = err
|
||||
{
|
||||
assert_eq!(e.found, i);
|
||||
assert_eq!(e.expected, large_stamp.len_as_bytes());
|
||||
assert_eq!(found, i);
|
||||
assert_eq!(expected, large_stamp.len_as_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -886,11 +890,13 @@ mod tests {
|
||||
let err = cuc.write_to_bytes(&mut buf[0..i]);
|
||||
assert!(err.is_err());
|
||||
let err = err.unwrap_err();
|
||||
if let TimestampError::ByteConversionError(ByteConversionError::ToSliceTooSmall(e)) =
|
||||
err
|
||||
if let TimestampError::ByteConversion(ByteConversionError::ToSliceTooSmall {
|
||||
found,
|
||||
expected,
|
||||
}) = err
|
||||
{
|
||||
assert_eq!(e.expected, cuc.len_as_bytes());
|
||||
assert_eq!(e.found, i);
|
||||
assert_eq!(expected, cuc.len_as_bytes());
|
||||
assert_eq!(found, i);
|
||||
} else {
|
||||
panic!("unexpected error: {}", err);
|
||||
}
|
||||
@ -903,9 +909,9 @@ mod tests {
|
||||
let res = TimeProviderCcsdsEpoch::from_bytes(&buf);
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
if let TimestampError::InvalidTimeCode(code, raw) = err {
|
||||
assert_eq!(code, CcsdsTimeCodes::CucCcsdsEpoch);
|
||||
assert_eq!(raw, CcsdsTimeCodes::CucAgencyEpoch as u8);
|
||||
if let TimestampError::InvalidTimeCode { expected, found } = err {
|
||||
assert_eq!(expected, CcsdsTimeCodes::CucCcsdsEpoch);
|
||||
assert_eq!(found, CcsdsTimeCodes::CucAgencyEpoch as u8);
|
||||
} else {
|
||||
panic!("unexpected error: {}", err);
|
||||
}
|
||||
|
@ -1,10 +1,11 @@
|
||||
//! CCSDS Time Code Formats according to [CCSDS 301.0-B-4](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use chrono::{DateTime, LocalResult, TimeZone, Utc};
|
||||
use core::cmp::Ordering;
|
||||
use core::fmt::{Display, Formatter};
|
||||
use core::ops::{Add, AddAssign};
|
||||
use core::time::Duration;
|
||||
use core::u8;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
#[cfg(not(feature = "std"))]
|
||||
@ -16,6 +17,8 @@ use serde::{Deserialize, Serialize};
|
||||
use std::error::Error;
|
||||
#[cfg(feature = "std")]
|
||||
use std::time::{SystemTime, SystemTimeError};
|
||||
#[cfg(feature = "std")]
|
||||
pub use std_mod::*;
|
||||
|
||||
pub mod ascii;
|
||||
pub mod cds;
|
||||
@ -61,66 +64,30 @@ pub fn ccsds_time_code_from_p_field(pfield: u8) -> Result<CcsdsTimeCodes, u8> {
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[non_exhaustive]
|
||||
pub enum TimestampError {
|
||||
/// Contains tuple where first value is the expected time code and the second
|
||||
/// value is the found raw value
|
||||
InvalidTimeCode(CcsdsTimeCodes, u8),
|
||||
ByteConversionError(ByteConversionError),
|
||||
CdsError(cds::CdsError),
|
||||
CucError(cuc::CucError),
|
||||
InvalidTimeCode { expected: CcsdsTimeCodes, found: u8 },
|
||||
ByteConversion(ByteConversionError),
|
||||
Cds(cds::CdsError),
|
||||
Cuc(cuc::CucError),
|
||||
DateBeforeCcsdsEpoch(DateTime<Utc>),
|
||||
CustomEpochNotSupported,
|
||||
}
|
||||
|
||||
impl From<cds::CdsError> for TimestampError {
|
||||
fn from(e: cds::CdsError) -> Self {
|
||||
TimestampError::CdsError(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<cuc::CucError> for TimestampError {
|
||||
fn from(e: cuc::CucError) -> Self {
|
||||
TimestampError::CucError(e)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum StdTimestampError {
|
||||
SystemTimeError(SystemTimeError),
|
||||
TimestampError(TimestampError),
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl From<TimestampError> for StdTimestampError {
|
||||
fn from(v: TimestampError) -> Self {
|
||||
Self::TimestampError(v)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl From<SystemTimeError> for StdTimestampError {
|
||||
fn from(v: SystemTimeError) -> Self {
|
||||
Self::SystemTimeError(v)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for TimestampError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
TimestampError::InvalidTimeCode(time_code, raw_val) => {
|
||||
TimestampError::InvalidTimeCode { expected, found } => {
|
||||
write!(
|
||||
f,
|
||||
"invalid raw time code value {raw_val} for time code {time_code:?}"
|
||||
"invalid raw time code value {found} for time code {expected:?}"
|
||||
)
|
||||
}
|
||||
TimestampError::CdsError(e) => {
|
||||
TimestampError::Cds(e) => {
|
||||
write!(f, "cds error {e}")
|
||||
}
|
||||
TimestampError::CucError(e) => {
|
||||
TimestampError::Cuc(e) => {
|
||||
write!(f, "cuc error {e}")
|
||||
}
|
||||
TimestampError::ByteConversionError(e) => {
|
||||
TimestampError::ByteConversion(e) => {
|
||||
write!(f, "byte conversion error {e}")
|
||||
}
|
||||
TimestampError::DateBeforeCcsdsEpoch(e) => {
|
||||
@ -137,13 +104,40 @@ impl Display for TimestampError {
|
||||
impl Error for TimestampError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
TimestampError::ByteConversionError(e) => Some(e),
|
||||
TimestampError::CdsError(e) => Some(e),
|
||||
TimestampError::CucError(e) => Some(e),
|
||||
TimestampError::ByteConversion(e) => Some(e),
|
||||
TimestampError::Cds(e) => Some(e),
|
||||
TimestampError::Cuc(e) => Some(e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<cds::CdsError> for TimestampError {
|
||||
fn from(e: cds::CdsError) -> Self {
|
||||
TimestampError::Cds(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<cuc::CucError> for TimestampError {
|
||||
fn from(e: cuc::CucError) -> Self {
|
||||
TimestampError::Cuc(e)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
||||
pub mod std_mod {
|
||||
use crate::time::TimestampError;
|
||||
use std::time::SystemTimeError;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Clone, Error)]
|
||||
pub enum StdTimestampError {
|
||||
#[error("system time error: {0}")]
|
||||
SystemTime(#[from] SystemTimeError),
|
||||
#[error("timestamp error: {0}")]
|
||||
Timestamp(#[from] TimestampError),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
||||
|
114
src/util.rs
114
src/util.rs
@ -1,4 +1,4 @@
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use core::fmt::{Debug, Display, Formatter};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
@ -80,12 +80,17 @@ pub trait UnsignedEnumExt: UnsignedEnum + Debug + Copy + Clone + PartialEq + Eq
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum UnsignedByteFieldError {
|
||||
/// Value is too large for specified width of byte field. The first value contains the width,
|
||||
/// the second value contains the detected value.
|
||||
ValueTooLargeForWidth((usize, u64)),
|
||||
/// Value is too large for specified width of byte field.
|
||||
ValueTooLargeForWidth {
|
||||
width: usize,
|
||||
value: u64,
|
||||
},
|
||||
/// Only 1, 2, 4 and 8 are allow width values. Optionally contains the expected width if
|
||||
/// applicable, for example for conversions.
|
||||
InvalidWidth(usize, Option<usize>),
|
||||
InvalidWidth {
|
||||
found: usize,
|
||||
expected: Option<usize>,
|
||||
},
|
||||
ByteConversionError(ByteConversionError),
|
||||
}
|
||||
|
||||
@ -101,10 +106,10 @@ impl Display for UnsignedByteFieldError {
|
||||
Self::ByteConversionError(e) => {
|
||||
write!(f, "low level byte conversion error: {e}")
|
||||
}
|
||||
Self::InvalidWidth(val, _) => {
|
||||
write!(f, "invalid width {val}, only 1, 2, 4 and 8 are allowed.")
|
||||
Self::InvalidWidth { found, .. } => {
|
||||
write!(f, "invalid width {found}, only 1, 2, 4 and 8 are allowed.")
|
||||
}
|
||||
Self::ValueTooLargeForWidth((width, value)) => {
|
||||
Self::ValueTooLargeForWidth { width, value } => {
|
||||
write!(f, "value {value} too large for width {width}")
|
||||
}
|
||||
}
|
||||
@ -123,7 +128,7 @@ pub struct UnsignedByteField {
|
||||
}
|
||||
|
||||
impl UnsignedByteField {
|
||||
pub fn new(width: usize, value: u64) -> Self {
|
||||
pub const fn new(width: usize, value: u64) -> Self {
|
||||
Self { width, value }
|
||||
}
|
||||
|
||||
@ -133,10 +138,10 @@ impl UnsignedByteField {
|
||||
|
||||
pub fn new_from_be_bytes(width: usize, buf: &[u8]) -> Result<Self, UnsignedByteFieldError> {
|
||||
if width > buf.len() {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
expected: width,
|
||||
found: buf.len(),
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
match width {
|
||||
@ -154,7 +159,10 @@ impl UnsignedByteField {
|
||||
width,
|
||||
u64::from_be_bytes(buf[0..8].try_into().unwrap()),
|
||||
)),
|
||||
_ => Err(UnsignedByteFieldError::InvalidWidth(width, None)),
|
||||
_ => Err(UnsignedByteFieldError::InvalidWidth {
|
||||
found: width,
|
||||
expected: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -166,10 +174,10 @@ impl UnsignedEnum for UnsignedByteField {
|
||||
|
||||
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
if buf.len() < self.size() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
expected: self.size(),
|
||||
found: buf.len(),
|
||||
}));
|
||||
});
|
||||
}
|
||||
match self.size() {
|
||||
0 => Ok(0),
|
||||
@ -204,7 +212,7 @@ pub struct GenericUnsignedByteField<TYPE> {
|
||||
}
|
||||
|
||||
impl<TYPE> GenericUnsignedByteField<TYPE> {
|
||||
pub fn new(val: TYPE) -> Self {
|
||||
pub const fn new(val: TYPE) -> Self {
|
||||
Self { value: val }
|
||||
}
|
||||
}
|
||||
@ -216,10 +224,10 @@ impl<TYPE: ToBeBytes> UnsignedEnum for GenericUnsignedByteField<TYPE> {
|
||||
|
||||
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
if buf.len() < self.size() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: self.size(),
|
||||
}));
|
||||
});
|
||||
}
|
||||
buf[0..self.size()].copy_from_slice(self.value.to_be_bytes().as_ref());
|
||||
Ok(self.value.written_len())
|
||||
@ -248,7 +256,10 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU8 {
|
||||
|
||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||
if value.width != 1 {
|
||||
return Err(UnsignedByteFieldError::InvalidWidth(value.width, Some(1)));
|
||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||
found: value.width,
|
||||
expected: Some(1),
|
||||
});
|
||||
}
|
||||
Ok(Self::new(value.value as u8))
|
||||
}
|
||||
@ -265,7 +276,10 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU16 {
|
||||
|
||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||
if value.width != 2 {
|
||||
return Err(UnsignedByteFieldError::InvalidWidth(value.width, Some(2)));
|
||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||
found: value.width,
|
||||
expected: Some(2),
|
||||
});
|
||||
}
|
||||
Ok(Self::new(value.value as u16))
|
||||
}
|
||||
@ -282,7 +296,10 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU32 {
|
||||
|
||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||
if value.width != 4 {
|
||||
return Err(UnsignedByteFieldError::InvalidWidth(value.width, Some(4)));
|
||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||
found: value.width,
|
||||
expected: Some(4),
|
||||
});
|
||||
}
|
||||
Ok(Self::new(value.value as u32))
|
||||
}
|
||||
@ -299,7 +316,10 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU64 {
|
||||
|
||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||
if value.width != 8 {
|
||||
return Err(UnsignedByteFieldError::InvalidWidth(value.width, Some(8)));
|
||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||
found: value.width,
|
||||
expected: Some(8),
|
||||
});
|
||||
}
|
||||
Ok(Self::new(value.value))
|
||||
}
|
||||
@ -393,8 +413,11 @@ pub mod tests {
|
||||
assert!(conv_fails.is_err());
|
||||
let err = conv_fails.unwrap_err();
|
||||
match err {
|
||||
UnsignedByteFieldError::InvalidWidth(width, Some(expected)) => {
|
||||
assert_eq!(width, 2);
|
||||
UnsignedByteFieldError::InvalidWidth {
|
||||
found,
|
||||
expected: Some(expected),
|
||||
} => {
|
||||
assert_eq!(found, 2);
|
||||
assert_eq!(expected, 1);
|
||||
}
|
||||
_ => {
|
||||
@ -422,8 +445,11 @@ pub mod tests {
|
||||
assert!(conv_fails.is_err());
|
||||
let err = conv_fails.unwrap_err();
|
||||
match err {
|
||||
UnsignedByteFieldError::InvalidWidth(width, Some(expected)) => {
|
||||
assert_eq!(width, 4);
|
||||
UnsignedByteFieldError::InvalidWidth {
|
||||
found,
|
||||
expected: Some(expected),
|
||||
} => {
|
||||
assert_eq!(found, 4);
|
||||
assert_eq!(expected, 2);
|
||||
}
|
||||
_ => {
|
||||
@ -451,8 +477,11 @@ pub mod tests {
|
||||
assert!(conv_fails.is_err());
|
||||
let err = conv_fails.unwrap_err();
|
||||
match err {
|
||||
UnsignedByteFieldError::InvalidWidth(width, Some(expected)) => {
|
||||
assert_eq!(width, 8);
|
||||
UnsignedByteFieldError::InvalidWidth {
|
||||
found,
|
||||
expected: Some(expected),
|
||||
} => {
|
||||
assert_eq!(found, 8);
|
||||
assert_eq!(expected, 4);
|
||||
}
|
||||
_ => {
|
||||
@ -480,8 +509,11 @@ pub mod tests {
|
||||
assert!(conv_fails.is_err());
|
||||
let err = conv_fails.unwrap_err();
|
||||
match err {
|
||||
UnsignedByteFieldError::InvalidWidth(width, Some(expected)) => {
|
||||
assert_eq!(width, 4);
|
||||
UnsignedByteFieldError::InvalidWidth {
|
||||
found,
|
||||
expected: Some(expected),
|
||||
} => {
|
||||
assert_eq!(found, 4);
|
||||
assert_eq!(expected, 8);
|
||||
}
|
||||
_ => {
|
||||
@ -582,9 +614,9 @@ pub mod tests {
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.found, 1);
|
||||
assert_eq!(missmatch.expected, 2);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(found, 1);
|
||||
assert_eq!(expected, 2);
|
||||
}
|
||||
_ => {
|
||||
panic!("invalid exception")
|
||||
@ -600,9 +632,9 @@ pub mod tests {
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.found, 1);
|
||||
assert_eq!(missmatch.expected, 2);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(found, 1);
|
||||
assert_eq!(expected, 2);
|
||||
}
|
||||
_ => {
|
||||
panic!("invalid exception {}", err)
|
||||
@ -612,11 +644,11 @@ pub mod tests {
|
||||
assert!(u16.is_err());
|
||||
let err = u16.unwrap_err();
|
||||
if let UnsignedByteFieldError::ByteConversionError(
|
||||
ByteConversionError::FromSliceTooSmall(missmatch),
|
||||
ByteConversionError::FromSliceTooSmall { found, expected },
|
||||
) = err
|
||||
{
|
||||
assert_eq!(missmatch.expected, 2);
|
||||
assert_eq!(missmatch.found, 1);
|
||||
assert_eq!(expected, 2);
|
||||
assert_eq!(found, 1);
|
||||
} else {
|
||||
panic!("unexpected exception {}", err);
|
||||
}
|
||||
@ -630,9 +662,9 @@ pub mod tests {
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.found, 3);
|
||||
assert_eq!(missmatch.expected, 4);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(found, 3);
|
||||
assert_eq!(expected, 4);
|
||||
}
|
||||
_ => {
|
||||
panic!("invalid exception")
|
||||
|
Reference in New Issue
Block a user