Compare commits
20 Commits
fe1a30327b
...
v0.3.0
Author | SHA1 | Date | |
---|---|---|---|
85bfcad111 | |||
03d112cbef | |||
1ec21c1bff | |||
c750f94fba | |||
1d6cf3a75d | |||
f8199ca87a | |||
4c1101f65f | |||
38b789ca6d | |||
d391891991 | |||
65e85f20e0 | |||
a2673c9870 | |||
603f688ac3 | |||
638e4cda62 | |||
1cc4771a53 | |||
427b368057 | |||
795abc57fa | |||
7da7e5329c | |||
5631372e58 | |||
28ba4f887d | |||
d559646d80 |
18
CHANGELOG.md
18
CHANGELOG.md
@ -8,6 +8,20 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
|
|||||||
|
|
||||||
# [unreleased]
|
# [unreleased]
|
||||||
|
|
||||||
|
# [v0.3.0] 01.12.2022
|
||||||
|
|
||||||
|
## Added
|
||||||
|
|
||||||
|
- `EcssEnumerationExt` trait which implements `Debug`, `Copy`, `Clone`,
|
||||||
|
`PartialEq` and `Eq` in addition to `EcssEnumeration`
|
||||||
|
|
||||||
|
## Changed
|
||||||
|
|
||||||
|
- `EcssEnumeration` trait: Rename `write_to_bytes`
|
||||||
|
to `write_to_be_bytes`
|
||||||
|
|
||||||
|
# [v0.2.0] 13.09.2022
|
||||||
|
|
||||||
## Added
|
## Added
|
||||||
|
|
||||||
- Basic support for ECSS enumeration types for u8, u16, u32 and u64
|
- Basic support for ECSS enumeration types for u8, u16, u32 and u64
|
||||||
@ -15,6 +29,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
|
|||||||
## Changed
|
## Changed
|
||||||
|
|
||||||
- Better names for generic error enumerations: `PacketError` renamed to `ByteConversionError`
|
- Better names for generic error enumerations: `PacketError` renamed to `ByteConversionError`
|
||||||
|
- CCSDS module: `ssc` abbreviations fully replaced by better name `seq_count`
|
||||||
|
- Time module: `CcsdsTimeProvider::date_time` now has `Option<DateTime<Utc>>` as
|
||||||
|
a returnvalue instead of `DateTime<Utc>`
|
||||||
|
- `PusTc` and `PusTm`: `new_from_raw_slice` renamed to simpler `from_bytes`
|
||||||
|
|
||||||
# [v0.1.0] 16.08.2022
|
# [v0.1.0] 16.08.2022
|
||||||
|
|
||||||
|
18
Cargo.toml
18
Cargo.toml
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "spacepackets"
|
name = "spacepackets"
|
||||||
version = "0.1.0"
|
version = "0.3.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
authors = ["Robin Mueller <muellerr@irs.uni-stuttgart.de>"]
|
authors = ["Robin Mueller <muellerr@irs.uni-stuttgart.de>"]
|
||||||
description = "Generic implementations for various CCSDS and ECSS packet standards"
|
description = "Generic implementations for various CCSDS and ECSS packet standards"
|
||||||
@ -12,17 +12,17 @@ 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
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
zerocopy = "0.6.1"
|
zerocopy = "0.6"
|
||||||
crc = "3.0.0"
|
crc = "3.0"
|
||||||
delegate = "0.7.0"
|
delegate = "0.8"
|
||||||
|
|
||||||
[dependencies.serde]
|
[dependencies.serde]
|
||||||
version = "1.0.142"
|
version = "1.0"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = ["derive"]
|
features = ["derive"]
|
||||||
|
|
||||||
[dependencies.chrono]
|
[dependencies.chrono]
|
||||||
version = "0.4.20"
|
version = "0.4"
|
||||||
default-features = false
|
default-features = false
|
||||||
|
|
||||||
[dependencies.num-traits]
|
[dependencies.num-traits]
|
||||||
@ -30,9 +30,13 @@ version = "0.2"
|
|||||||
default-features = false
|
default-features = false
|
||||||
|
|
||||||
[dev-dependencies.postcard]
|
[dev-dependencies.postcard]
|
||||||
version = "1.0.1"
|
version = "1.0"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["std"]
|
default = ["std"]
|
||||||
std = ["chrono/std", "chrono/clock", "alloc"]
|
std = ["chrono/std", "chrono/clock", "alloc"]
|
||||||
alloc = ["postcard/alloc"]
|
alloc = ["postcard/alloc"]
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
all-features = true
|
||||||
|
rustdoc-args = ["--cfg", "doc_cfg"]
|
||||||
|
11
README.md
11
README.md
@ -20,11 +20,9 @@ Currently, this includes the following components:
|
|||||||
|
|
||||||
# Features
|
# Features
|
||||||
|
|
||||||
`spacepackets` supports various runtime environments and is also suitable
|
`spacepackets` supports various runtime environments and is also suitable for `no_std` environments.
|
||||||
for suitable for `no_std` environments. It has several features which may be enabled
|
|
||||||
for disabled.
|
|
||||||
|
|
||||||
It also offers support for [`serde`](https://serde.rs/). The Space Paccket, PUS TM and TC
|
It offers support for [`serde`](https://serde.rs/). The Space Packet, PUS TM and TC
|
||||||
implementations derive the `serde` `Serialize` and `Deserialize` trait. This allows serializing and
|
implementations derive the `serde` `Serialize` and `Deserialize` trait. This allows serializing and
|
||||||
deserializing them with an appropriate `serde` provider like
|
deserializing them with an appropriate `serde` provider like
|
||||||
[`postcard`](https://github.com/jamesmunns/postcard).
|
[`postcard`](https://github.com/jamesmunns/postcard).
|
||||||
@ -35,3 +33,8 @@ Default features:
|
|||||||
- [`alloc`](https://doc.rust-lang.org/alloc/): Enables features which operate on containers
|
- [`alloc`](https://doc.rust-lang.org/alloc/): Enables features which operate on containers
|
||||||
like [`alloc::vec::Vec`](https://doc.rust-lang.org/beta/alloc/vec/struct.Vec.html).
|
like [`alloc::vec::Vec`](https://doc.rust-lang.org/beta/alloc/vec/struct.Vec.html).
|
||||||
Enabled by the `std` feature.
|
Enabled by the `std` feature.
|
||||||
|
|
||||||
|
# Examples
|
||||||
|
|
||||||
|
You can check the [documentation](https://docs.rs/spacepackets) of individual modules for various
|
||||||
|
usage examples.
|
||||||
|
58
src/ecss.rs
58
src/ecss.rs
@ -1,6 +1,7 @@
|
|||||||
//! Common definitions and helpers required to create PUS TMTC packets according to
|
//! 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/)
|
//! [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::{ByteConversionError, CcsdsPacket, SizeMissmatch};
|
use crate::{ByteConversionError, CcsdsPacket, SizeMissmatch};
|
||||||
|
use core::fmt::Debug;
|
||||||
use core::mem::size_of;
|
use core::mem::size_of;
|
||||||
use crc::{Crc, CRC_16_IBM_3740};
|
use crc::{Crc, CRC_16_IBM_3740};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@ -33,6 +34,22 @@ impl TryFrom<u8> for PusVersion {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
|
pub enum PacketTypeCodes {
|
||||||
|
Boolean = 1,
|
||||||
|
Enumerated = 2,
|
||||||
|
UnsignedInt = 3,
|
||||||
|
SignedInt = 4,
|
||||||
|
Real = 5,
|
||||||
|
BitString = 6,
|
||||||
|
OctetString = 7,
|
||||||
|
CharString = 8,
|
||||||
|
AbsoluteTime = 9,
|
||||||
|
RelativeTime = 10,
|
||||||
|
Deduced = 11,
|
||||||
|
Packet = 12,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
pub enum PusError {
|
pub enum PusError {
|
||||||
VersionNotSupported(PusVersion),
|
VersionNotSupported(PusVersion),
|
||||||
@ -41,7 +58,13 @@ pub enum PusError {
|
|||||||
NoRawData,
|
NoRawData,
|
||||||
/// CRC16 needs to be calculated first
|
/// CRC16 needs to be calculated first
|
||||||
CrcCalculationMissing,
|
CrcCalculationMissing,
|
||||||
PacketError(ByteConversionError),
|
ByteConversionError(ByteConversionError),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ByteConversionError> for PusError {
|
||||||
|
fn from(e: ByteConversionError) -> Self {
|
||||||
|
PusError::ByteConversionError(e)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait PusPacket: CcsdsPacket {
|
pub trait PusPacket: CcsdsPacket {
|
||||||
@ -136,15 +159,22 @@ macro_rules! sp_header_impls {
|
|||||||
pub(crate) use ccsds_impl;
|
pub(crate) use ccsds_impl;
|
||||||
pub(crate) use sp_header_impls;
|
pub(crate) use sp_header_impls;
|
||||||
|
|
||||||
|
/// Generic trait for ECSS enumeration which consist of a PFC field denoting their bit length
|
||||||
|
/// and an unsigned value. The trait makes no assumptions about the actual type of the unsigned
|
||||||
|
/// value and only requires implementors to implement a function which writes the enumeration into
|
||||||
|
/// a raw byte format.
|
||||||
pub trait EcssEnumeration {
|
pub trait EcssEnumeration {
|
||||||
|
/// Packet Format Code, which denotes the number of bits of the enumeration
|
||||||
fn pfc(&self) -> u8;
|
fn pfc(&self) -> u8;
|
||||||
fn byte_width(&self) -> usize {
|
fn byte_width(&self) -> usize {
|
||||||
(self.pfc() / 8) as usize
|
(self.pfc() / 8) as usize
|
||||||
}
|
}
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<(), ByteConversionError>;
|
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<(), ByteConversionError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
trait ToBeBytes {
|
pub trait EcssEnumerationExt: EcssEnumeration + Debug + Copy + Clone + PartialEq + Eq {}
|
||||||
|
|
||||||
|
pub trait ToBeBytes {
|
||||||
type ByteArray: AsRef<[u8]>;
|
type ByteArray: AsRef<[u8]>;
|
||||||
fn to_be_bytes(&self) -> Self::ByteArray;
|
fn to_be_bytes(&self) -> Self::ByteArray;
|
||||||
}
|
}
|
||||||
@ -181,11 +211,16 @@ impl ToBeBytes for u64 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||||
pub struct GenericEcssEnumWrapper<TYPE> {
|
pub struct GenericEcssEnumWrapper<TYPE> {
|
||||||
val: TYPE,
|
val: TYPE,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<TYPE> GenericEcssEnumWrapper<TYPE> {
|
impl<TYPE> GenericEcssEnumWrapper<TYPE> {
|
||||||
|
pub const fn ptc() -> PacketTypeCodes {
|
||||||
|
PacketTypeCodes::Enumerated
|
||||||
|
}
|
||||||
|
|
||||||
pub fn new(val: TYPE) -> Self {
|
pub fn new(val: TYPE) -> Self {
|
||||||
Self { val }
|
Self { val }
|
||||||
}
|
}
|
||||||
@ -196,7 +231,7 @@ impl<TYPE: ToBeBytes> EcssEnumeration for GenericEcssEnumWrapper<TYPE> {
|
|||||||
size_of::<TYPE>() as u8 * 8_u8
|
size_of::<TYPE>() as u8 * 8_u8
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<(), ByteConversionError> {
|
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<(), ByteConversionError> {
|
||||||
if buf.len() < self.byte_width() as usize {
|
if buf.len() < self.byte_width() as usize {
|
||||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||||
found: buf.len(),
|
found: buf.len(),
|
||||||
@ -208,6 +243,11 @@ impl<TYPE: ToBeBytes> EcssEnumeration for GenericEcssEnumWrapper<TYPE> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<TYPE: Debug + Copy + Clone + PartialEq + Eq + ToBeBytes> EcssEnumerationExt
|
||||||
|
for GenericEcssEnumWrapper<TYPE>
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
pub type EcssEnumU8 = GenericEcssEnumWrapper<u8>;
|
pub type EcssEnumU8 = GenericEcssEnumWrapper<u8>;
|
||||||
pub type EcssEnumU16 = GenericEcssEnumWrapper<u16>;
|
pub type EcssEnumU16 = GenericEcssEnumWrapper<u16>;
|
||||||
pub type EcssEnumU32 = GenericEcssEnumWrapper<u32>;
|
pub type EcssEnumU32 = GenericEcssEnumWrapper<u32>;
|
||||||
@ -223,7 +263,7 @@ mod tests {
|
|||||||
let mut buf = [0, 0, 0];
|
let mut buf = [0, 0, 0];
|
||||||
let my_enum = EcssEnumU8::new(1);
|
let my_enum = EcssEnumU8::new(1);
|
||||||
my_enum
|
my_enum
|
||||||
.write_to_bytes(&mut buf[1..2])
|
.write_to_be_bytes(&mut buf[1..2])
|
||||||
.expect("To byte conversion of u8 failed");
|
.expect("To byte conversion of u8 failed");
|
||||||
assert_eq!(buf[1], 1);
|
assert_eq!(buf[1], 1);
|
||||||
}
|
}
|
||||||
@ -233,7 +273,7 @@ mod tests {
|
|||||||
let mut buf = [0, 0, 0];
|
let mut buf = [0, 0, 0];
|
||||||
let my_enum = EcssEnumU16::new(0x1f2f);
|
let my_enum = EcssEnumU16::new(0x1f2f);
|
||||||
my_enum
|
my_enum
|
||||||
.write_to_bytes(&mut buf[1..3])
|
.write_to_be_bytes(&mut buf[1..3])
|
||||||
.expect("To byte conversion of u8 failed");
|
.expect("To byte conversion of u8 failed");
|
||||||
assert_eq!(buf[1], 0x1f);
|
assert_eq!(buf[1], 0x1f);
|
||||||
assert_eq!(buf[2], 0x2f);
|
assert_eq!(buf[2], 0x2f);
|
||||||
@ -243,7 +283,7 @@ mod tests {
|
|||||||
fn test_slice_u16_too_small() {
|
fn test_slice_u16_too_small() {
|
||||||
let mut buf = [0];
|
let mut buf = [0];
|
||||||
let my_enum = EcssEnumU16::new(0x1f2f);
|
let my_enum = EcssEnumU16::new(0x1f2f);
|
||||||
let res = my_enum.write_to_bytes(&mut buf[0..1]);
|
let res = my_enum.write_to_be_bytes(&mut buf[0..1]);
|
||||||
assert!(res.is_err());
|
assert!(res.is_err());
|
||||||
let error = res.unwrap_err();
|
let error = res.unwrap_err();
|
||||||
match error {
|
match error {
|
||||||
@ -262,7 +302,7 @@ mod tests {
|
|||||||
let mut buf = [0, 0, 0, 0, 0];
|
let mut buf = [0, 0, 0, 0, 0];
|
||||||
let my_enum = EcssEnumU32::new(0x1f2f3f4f);
|
let my_enum = EcssEnumU32::new(0x1f2f3f4f);
|
||||||
my_enum
|
my_enum
|
||||||
.write_to_bytes(&mut buf[1..5])
|
.write_to_be_bytes(&mut buf[1..5])
|
||||||
.expect("To byte conversion of u8 failed");
|
.expect("To byte conversion of u8 failed");
|
||||||
assert_eq!(buf[1], 0x1f);
|
assert_eq!(buf[1], 0x1f);
|
||||||
assert_eq!(buf[2], 0x2f);
|
assert_eq!(buf[2], 0x2f);
|
||||||
@ -274,7 +314,7 @@ mod tests {
|
|||||||
fn test_slice_u32_too_small() {
|
fn test_slice_u32_too_small() {
|
||||||
let mut buf = [0, 0, 0, 0, 0];
|
let mut buf = [0, 0, 0, 0, 0];
|
||||||
let my_enum = EcssEnumU32::new(0x1f2f3f4f);
|
let my_enum = EcssEnumU32::new(0x1f2f3f4f);
|
||||||
let res = my_enum.write_to_bytes(&mut buf[0..3]);
|
let res = my_enum.write_to_be_bytes(&mut buf[0..3]);
|
||||||
assert!(res.is_err());
|
assert!(res.is_err());
|
||||||
let error = res.unwrap_err();
|
let error = res.unwrap_err();
|
||||||
match error {
|
match error {
|
||||||
|
37
src/lib.rs
37
src/lib.rs
@ -14,11 +14,9 @@
|
|||||||
//!
|
//!
|
||||||
//! ## Features
|
//! ## Features
|
||||||
//!
|
//!
|
||||||
//! `spacepackets` supports various runtime environments and is also suitable
|
//! `spacepackets` supports various runtime environments and is also suitable for `no_std` environments.
|
||||||
//! for suitable for `no_std` environments. It has several features which may be enabled
|
|
||||||
//! for disabled.
|
|
||||||
//!
|
//!
|
||||||
//! It also offers support for [`serde`](https://serde.rs/). The Space Paccket, PUS TM and TC
|
//! It also offers support for [`serde`](https://serde.rs/). The Space Packet, PUS TM and TC
|
||||||
//! implementations derive the `serde` `Serialize` and `Deserialize` trait. This allows serializing and
|
//! implementations derive the `serde` `Serialize` and `Deserialize` trait. This allows serializing and
|
||||||
//! deserializing them with an appropriate `serde` provider like
|
//! deserializing them with an appropriate `serde` provider like
|
||||||
//! [`postcard`](https://github.com/jamesmunns/postcard).
|
//! [`postcard`](https://github.com/jamesmunns/postcard).
|
||||||
@ -60,17 +58,19 @@ pub mod time;
|
|||||||
pub mod tm;
|
pub mod tm;
|
||||||
|
|
||||||
pub const MAX_APID: u16 = 2u16.pow(11) - 1;
|
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)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
pub struct SizeMissmatch {
|
pub struct SizeMissmatch {
|
||||||
pub found: usize,
|
pub found: usize,
|
||||||
pub expected: usize,
|
pub expected: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
pub enum ByteConversionError {
|
pub enum ByteConversionError {
|
||||||
/// The passed slice is too small. Returns the found and expected minimum size
|
/// The passed slice is too small. Returns the passed slice length and expected minimum size
|
||||||
ToSliceTooSmall(SizeMissmatch),
|
ToSliceTooSmall(SizeMissmatch),
|
||||||
/// The provider buffer it soo small. Returns the found and expected minimum size
|
/// The provider buffer is too small. Returns the passed slice length and expected minimum size
|
||||||
FromSliceTooSmall(SizeMissmatch),
|
FromSliceTooSmall(SizeMissmatch),
|
||||||
/// The [zerocopy] library failed to write to bytes
|
/// The [zerocopy] library failed to write to bytes
|
||||||
ZeroCopyToError,
|
ZeroCopyToError,
|
||||||
@ -137,7 +137,7 @@ impl PacketId {
|
|||||||
sec_header_flag,
|
sec_header_flag,
|
||||||
apid: 0,
|
apid: 0,
|
||||||
};
|
};
|
||||||
pid.set_apid(apid).then(|| pid)
|
pid.set_apid(apid).then_some(pid)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a new Application Process ID (APID). If the passed number is invalid, the APID will
|
/// Set a new Application Process ID (APID). If the passed number is invalid, the APID will
|
||||||
@ -177,12 +177,13 @@ pub struct PacketSequenceCtrl {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PacketSequenceCtrl {
|
impl PacketSequenceCtrl {
|
||||||
pub fn new(seq_flags: SequenceFlags, ssc: u16) -> Option<PacketSequenceCtrl> {
|
/// Returns [None] if the passed sequence count exceeds [MAX_SEQ_COUNT]
|
||||||
|
pub fn new(seq_flags: SequenceFlags, seq_count: u16) -> Option<PacketSequenceCtrl> {
|
||||||
let mut psc = PacketSequenceCtrl {
|
let mut psc = PacketSequenceCtrl {
|
||||||
seq_flags,
|
seq_flags,
|
||||||
seq_count: 0,
|
seq_count: 0,
|
||||||
};
|
};
|
||||||
psc.set_seq_count(ssc).then(|| psc)
|
psc.set_seq_count(seq_count).then_some(psc)
|
||||||
}
|
}
|
||||||
pub fn raw(&self) -> u16 {
|
pub fn raw(&self) -> u16 {
|
||||||
((self.seq_flags as u16) << 14) | self.seq_count
|
((self.seq_flags as u16) << 14) | self.seq_count
|
||||||
@ -191,14 +192,14 @@ impl PacketSequenceCtrl {
|
|||||||
/// Set a new sequence count. If the passed number is invalid, the sequence count will not be
|
/// Set a new sequence count. If the passed number is invalid, the sequence count will not be
|
||||||
/// set and false will be returned. The maximum allowed value for the 14-bit field is 16383
|
/// set and false will be returned. The maximum allowed value for the 14-bit field is 16383
|
||||||
pub fn set_seq_count(&mut self, ssc: u16) -> bool {
|
pub fn set_seq_count(&mut self, ssc: u16) -> bool {
|
||||||
if ssc > 2u16.pow(14) - 1 {
|
if ssc > MAX_SEQ_COUNT {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
self.seq_count = ssc;
|
self.seq_count = ssc;
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn ssc(&self) -> u16 {
|
pub fn seq_count(&self) -> u16 {
|
||||||
self.seq_count
|
self.seq_count
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -323,6 +324,7 @@ pub struct SpHeader {
|
|||||||
pub psc: PacketSequenceCtrl,
|
pub psc: PacketSequenceCtrl,
|
||||||
pub data_len: u16,
|
pub data_len: u16,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for SpHeader {
|
impl Default for SpHeader {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
SpHeader {
|
SpHeader {
|
||||||
@ -341,29 +343,36 @@ impl Default for SpHeader {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl SpHeader {
|
impl SpHeader {
|
||||||
|
/// Create a new Space Packet Header instance which can be used to create generic
|
||||||
|
/// Space Packets. This will return [None] if the APID or sequence count argument
|
||||||
|
/// exceed [MAX_APID] or [MAX_SEQ_COUNT] respectively.
|
||||||
pub fn new(
|
pub fn new(
|
||||||
ptype: PacketType,
|
ptype: PacketType,
|
||||||
sec_header: bool,
|
sec_header: bool,
|
||||||
apid: u16,
|
apid: u16,
|
||||||
ssc: u16,
|
seq_count: u16,
|
||||||
data_len: u16,
|
data_len: u16,
|
||||||
) -> Option<Self> {
|
) -> Option<Self> {
|
||||||
if ssc > 2u16.pow(14) - 1 || apid > MAX_APID {
|
if seq_count > MAX_SEQ_COUNT || apid > MAX_APID {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let mut header = SpHeader::default();
|
let mut header = SpHeader::default();
|
||||||
header.packet_id.sec_header_flag = sec_header;
|
header.packet_id.sec_header_flag = sec_header;
|
||||||
header.packet_id.apid = apid;
|
header.packet_id.apid = apid;
|
||||||
header.packet_id.ptype = ptype;
|
header.packet_id.ptype = ptype;
|
||||||
header.psc.seq_count = ssc;
|
header.psc.seq_count = seq_count;
|
||||||
header.data_len = data_len;
|
header.data_len = data_len;
|
||||||
Some(header)
|
Some(header)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Helper function for telemetry space packet headers. The packet type field will be
|
||||||
|
/// set accordingly.
|
||||||
pub fn tm(apid: u16, seq_count: u16, data_len: u16) -> Option<Self> {
|
pub fn tm(apid: u16, seq_count: u16, data_len: u16) -> Option<Self> {
|
||||||
Self::new(PacketType::Tm, false, apid, seq_count, data_len)
|
Self::new(PacketType::Tm, false, apid, seq_count, data_len)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Helper function for telecommand space packet headers. The packet type field will be
|
||||||
|
/// set accordingly.
|
||||||
pub fn tc(apid: u16, seq_count: u16, data_len: u16) -> Option<Self> {
|
pub fn tc(apid: u16, seq_count: u16, data_len: u16) -> Option<Self> {
|
||||||
Self::new(PacketType::Tc, false, apid, seq_count, data_len)
|
Self::new(PacketType::Tc, false, apid, seq_count, data_len)
|
||||||
}
|
}
|
||||||
|
40
src/tc.rs
40
src/tc.rs
@ -26,7 +26,7 @@
|
|||||||
//! println!("{:?}", &test_buf[0..size]);
|
//! println!("{:?}", &test_buf[0..size]);
|
||||||
//!
|
//!
|
||||||
//! // Deserialize from the raw byte representation
|
//! // Deserialize from the raw byte representation
|
||||||
//! let pus_tc_deserialized = PusTc::new_from_raw_slice(&test_buf).expect("Deserialization failed");
|
//! let pus_tc_deserialized = PusTc::from_bytes(&test_buf).expect("Deserialization failed");
|
||||||
//! assert_eq!(pus_tc.service(), 17);
|
//! assert_eq!(pus_tc.service(), 17);
|
||||||
//! assert_eq!(pus_tc.subservice(), 1);
|
//! assert_eq!(pus_tc.subservice(), 1);
|
||||||
//! assert_eq!(pus_tc.apid(), 0x02);
|
//! assert_eq!(pus_tc.apid(), 0x02);
|
||||||
@ -336,22 +336,21 @@ impl<'slice> PusTc<'slice> {
|
|||||||
let tc_header_len = size_of::<zc::PusTcSecondaryHeader>();
|
let tc_header_len = size_of::<zc::PusTcSecondaryHeader>();
|
||||||
let total_size = self.len_packed();
|
let total_size = self.len_packed();
|
||||||
if total_size > slice.len() {
|
if total_size > slice.len() {
|
||||||
return Err(PusError::PacketError(ByteConversionError::ToSliceTooSmall(
|
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||||
SizeMissmatch {
|
found: slice.len(),
|
||||||
found: slice.len(),
|
expected: total_size,
|
||||||
expected: total_size,
|
})
|
||||||
},
|
.into());
|
||||||
)));
|
|
||||||
}
|
}
|
||||||
sph_zc
|
sph_zc
|
||||||
.to_bytes(&mut slice[curr_idx..curr_idx + CCSDS_HEADER_LEN])
|
.to_bytes(&mut slice[curr_idx..curr_idx + CCSDS_HEADER_LEN])
|
||||||
.ok_or(PusError::PacketError(ByteConversionError::ZeroCopyToError))?;
|
.ok_or(ByteConversionError::ZeroCopyToError)?;
|
||||||
|
|
||||||
curr_idx += CCSDS_HEADER_LEN;
|
curr_idx += CCSDS_HEADER_LEN;
|
||||||
let sec_header = zc::PusTcSecondaryHeader::try_from(self.sec_header).unwrap();
|
let sec_header = zc::PusTcSecondaryHeader::try_from(self.sec_header).unwrap();
|
||||||
sec_header
|
sec_header
|
||||||
.write_to_bytes(&mut slice[curr_idx..curr_idx + tc_header_len])
|
.write_to_bytes(&mut slice[curr_idx..curr_idx + tc_header_len])
|
||||||
.ok_or(PusError::PacketError(ByteConversionError::ZeroCopyToError))?;
|
.ok_or(ByteConversionError::ZeroCopyToError)?;
|
||||||
|
|
||||||
curr_idx += tc_header_len;
|
curr_idx += tc_header_len;
|
||||||
if let Some(app_data) = self.app_data {
|
if let Some(app_data) = self.app_data {
|
||||||
@ -371,6 +370,7 @@ impl<'slice> PusTc<'slice> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "alloc")]
|
#[cfg(feature = "alloc")]
|
||||||
|
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
||||||
pub fn append_to_vec(&self, vec: &mut Vec<u8>) -> Result<usize, PusError> {
|
pub fn append_to_vec(&self, vec: &mut Vec<u8>) -> Result<usize, PusError> {
|
||||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||||
let mut appended_len = PUS_TC_MIN_LEN_WITHOUT_APP_DATA;
|
let mut appended_len = PUS_TC_MIN_LEN_WITHOUT_APP_DATA;
|
||||||
@ -402,7 +402,7 @@ impl<'slice> PusTc<'slice> {
|
|||||||
|
|
||||||
/// Create a [PusTc] instance from a raw slice. On success, it returns a tuple containing
|
/// 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
|
/// the instance and the found byte length of the packet
|
||||||
pub fn new_from_raw_slice(slice: &'slice [u8]) -> Result<(Self, usize), PusError> {
|
pub fn from_bytes(slice: &'slice [u8]) -> Result<(Self, usize), PusError> {
|
||||||
let raw_data_len = slice.len();
|
let raw_data_len = slice.len();
|
||||||
if raw_data_len < PUS_TC_MIN_LEN_WITHOUT_APP_DATA {
|
if raw_data_len < PUS_TC_MIN_LEN_WITHOUT_APP_DATA {
|
||||||
return Err(PusError::RawDataTooShort(raw_data_len));
|
return Err(PusError::RawDataTooShort(raw_data_len));
|
||||||
@ -410,9 +410,7 @@ impl<'slice> PusTc<'slice> {
|
|||||||
let mut current_idx = 0;
|
let mut current_idx = 0;
|
||||||
let sph =
|
let sph =
|
||||||
crate::zc::SpHeader::from_bytes(&slice[current_idx..current_idx + CCSDS_HEADER_LEN])
|
crate::zc::SpHeader::from_bytes(&slice[current_idx..current_idx + CCSDS_HEADER_LEN])
|
||||||
.ok_or(PusError::PacketError(
|
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||||
ByteConversionError::ZeroCopyFromError,
|
|
||||||
))?;
|
|
||||||
current_idx += CCSDS_HEADER_LEN;
|
current_idx += CCSDS_HEADER_LEN;
|
||||||
let total_len = sph.total_len();
|
let total_len = sph.total_len();
|
||||||
if raw_data_len < total_len || total_len < PUS_TC_MIN_LEN_WITHOUT_APP_DATA {
|
if raw_data_len < total_len || total_len < PUS_TC_MIN_LEN_WITHOUT_APP_DATA {
|
||||||
@ -421,9 +419,7 @@ impl<'slice> PusTc<'slice> {
|
|||||||
let sec_header = zc::PusTcSecondaryHeader::from_bytes(
|
let sec_header = zc::PusTcSecondaryHeader::from_bytes(
|
||||||
&slice[current_idx..current_idx + PUC_TC_SECONDARY_HEADER_LEN],
|
&slice[current_idx..current_idx + PUC_TC_SECONDARY_HEADER_LEN],
|
||||||
)
|
)
|
||||||
.ok_or(PusError::PacketError(
|
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||||
ByteConversionError::ZeroCopyFromError,
|
|
||||||
))?;
|
|
||||||
current_idx += PUC_TC_SECONDARY_HEADER_LEN;
|
current_idx += PUC_TC_SECONDARY_HEADER_LEN;
|
||||||
let raw_data = &slice[0..total_len];
|
let raw_data = &slice[0..total_len];
|
||||||
let pus_tc = PusTc {
|
let pus_tc = PusTc {
|
||||||
@ -527,8 +523,8 @@ mod tests {
|
|||||||
.write_to_bytes(test_buf.as_mut_slice())
|
.write_to_bytes(test_buf.as_mut_slice())
|
||||||
.expect("Error writing TC to buffer");
|
.expect("Error writing TC to buffer");
|
||||||
assert_eq!(size, 13);
|
assert_eq!(size, 13);
|
||||||
let (tc_from_raw, size) = PusTc::new_from_raw_slice(&test_buf)
|
let (tc_from_raw, size) =
|
||||||
.expect("Creating PUS TC struct from raw buffer failed");
|
PusTc::from_bytes(&test_buf).expect("Creating PUS TC struct from raw buffer failed");
|
||||||
assert_eq!(size, 13);
|
assert_eq!(size, 13);
|
||||||
verify_test_tc(&tc_from_raw, false, 13);
|
verify_test_tc(&tc_from_raw, false, 13);
|
||||||
assert!(tc_from_raw.user_data().is_none());
|
assert!(tc_from_raw.user_data().is_none());
|
||||||
@ -553,8 +549,8 @@ mod tests {
|
|||||||
.write_to_bytes(test_buf.as_mut_slice())
|
.write_to_bytes(test_buf.as_mut_slice())
|
||||||
.expect("Error writing TC to buffer");
|
.expect("Error writing TC to buffer");
|
||||||
assert_eq!(size, 16);
|
assert_eq!(size, 16);
|
||||||
let (tc_from_raw, size) = PusTc::new_from_raw_slice(&test_buf)
|
let (tc_from_raw, size) =
|
||||||
.expect("Creating PUS TC struct from raw buffer failed");
|
PusTc::from_bytes(&test_buf).expect("Creating PUS TC struct from raw buffer failed");
|
||||||
assert_eq!(size, 16);
|
assert_eq!(size, 16);
|
||||||
verify_test_tc(&tc_from_raw, true, 16);
|
verify_test_tc(&tc_from_raw, true, 16);
|
||||||
let user_data = tc_from_raw.user_data().unwrap();
|
let user_data = tc_from_raw.user_data().unwrap();
|
||||||
@ -584,7 +580,7 @@ mod tests {
|
|||||||
.write_to_bytes(test_buf.as_mut_slice())
|
.write_to_bytes(test_buf.as_mut_slice())
|
||||||
.expect("Error writing TC to buffer");
|
.expect("Error writing TC to buffer");
|
||||||
test_buf[12] = 0;
|
test_buf[12] = 0;
|
||||||
let res = PusTc::new_from_raw_slice(&test_buf);
|
let res = PusTc::from_bytes(&test_buf);
|
||||||
assert!(res.is_err());
|
assert!(res.is_err());
|
||||||
let err = res.unwrap_err();
|
let err = res.unwrap_err();
|
||||||
assert!(matches!(err, PusError::IncorrectCrc { .. }));
|
assert!(matches!(err, PusError::IncorrectCrc { .. }));
|
||||||
@ -636,7 +632,7 @@ mod tests {
|
|||||||
assert!(res.is_err());
|
assert!(res.is_err());
|
||||||
let err = res.unwrap_err();
|
let err = res.unwrap_err();
|
||||||
match err {
|
match err {
|
||||||
PusError::PacketError(err) => match err {
|
PusError::ByteConversionError(err) => match err {
|
||||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||||
assert_eq!(missmatch.expected, pus_tc.len_packed());
|
assert_eq!(missmatch.expected, pus_tc.len_packed());
|
||||||
assert_eq!(missmatch.found, 12);
|
assert_eq!(missmatch.found, 12);
|
||||||
|
73
src/time.rs
73
src/time.rs
@ -1,6 +1,6 @@
|
|||||||
//! CCSDS Time Code Formats according to [CCSDS 301.0-B-4](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
|
//! 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, SizeMissmatch};
|
||||||
use chrono::{DateTime, TimeZone, Utc};
|
use chrono::{DateTime, LocalResult, TimeZone, Utc};
|
||||||
|
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
#[cfg(not(feature = "std"))]
|
#[cfg(not(feature = "std"))]
|
||||||
@ -23,6 +23,8 @@ pub enum CcsdsTimeCodes {
|
|||||||
Ccs = 0b101,
|
Ccs = 0b101,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CDS_SHORT_P_FIELD: u8 = (CcsdsTimeCodes::Cds as u8) << 4;
|
||||||
|
|
||||||
impl TryFrom<u8> for CcsdsTimeCodes {
|
impl TryFrom<u8> for CcsdsTimeCodes {
|
||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
@ -47,6 +49,7 @@ pub enum TimestampError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
|
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
||||||
pub fn seconds_since_epoch() -> f64 {
|
pub fn seconds_since_epoch() -> f64 {
|
||||||
SystemTime::now()
|
SystemTime::now()
|
||||||
.duration_since(SystemTime::UNIX_EPOCH)
|
.duration_since(SystemTime::UNIX_EPOCH)
|
||||||
@ -91,12 +94,26 @@ pub trait CcsdsTimeProvider {
|
|||||||
fn p_field(&self) -> (usize, [u8; 2]);
|
fn p_field(&self) -> (usize, [u8; 2]);
|
||||||
fn ccdsd_time_code(&self) -> CcsdsTimeCodes;
|
fn ccdsd_time_code(&self) -> CcsdsTimeCodes;
|
||||||
fn unix_seconds(&self) -> i64;
|
fn unix_seconds(&self) -> i64;
|
||||||
fn date_time(&self) -> DateTime<Utc>;
|
fn date_time(&self) -> Option<DateTime<Utc>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This object is the abstraction for the CCSDS Day Segmented Time Code (CDS).
|
||||||
|
///
|
||||||
|
/// It has the capability to generate and read timestamps as specified in the CCSDS 301.0-B-4
|
||||||
|
/// section 3.3
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use spacepackets::time::{CdsShortTimeProvider, TimeWriter};
|
||||||
|
/// use spacepackets::time::CcsdsTimeCodes::Cds;
|
||||||
|
/// let timestamp_now = CdsShortTimeProvider::from_now().unwrap();
|
||||||
|
/// let mut raw_stamp = [0; 7];
|
||||||
|
/// timestamp_now.write_to_bytes(&mut raw_stamp).unwrap();
|
||||||
|
/// assert_eq!((raw_stamp[0] >> 4) & 0b111, Cds as u8);
|
||||||
|
/// ```
|
||||||
#[derive(Debug, Copy, Clone, Default)]
|
#[derive(Debug, Copy, Clone, Default)]
|
||||||
pub struct CdsShortTimeProvider {
|
pub struct CdsShortTimeProvider {
|
||||||
pfield: u8,
|
|
||||||
ccsds_days: u16,
|
ccsds_days: u16,
|
||||||
ms_of_day: u32,
|
ms_of_day: u32,
|
||||||
unix_seconds: i64,
|
unix_seconds: i64,
|
||||||
@ -106,7 +123,6 @@ pub struct CdsShortTimeProvider {
|
|||||||
impl CdsShortTimeProvider {
|
impl CdsShortTimeProvider {
|
||||||
pub fn new(ccsds_days: u16, ms_of_day: u32) -> Self {
|
pub fn new(ccsds_days: u16, ms_of_day: u32) -> Self {
|
||||||
let provider = Self {
|
let provider = Self {
|
||||||
pfield: (CcsdsTimeCodes::Cds as u8) << 4,
|
|
||||||
ccsds_days,
|
ccsds_days,
|
||||||
ms_of_day,
|
ms_of_day,
|
||||||
unix_seconds: 0,
|
unix_seconds: 0,
|
||||||
@ -118,6 +134,7 @@ impl CdsShortTimeProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
|
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
||||||
pub fn from_now() -> Result<Self, SystemTimeError> {
|
pub fn from_now() -> Result<Self, SystemTimeError> {
|
||||||
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
|
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
|
||||||
let epoch = now.as_secs();
|
let epoch = now.as_secs();
|
||||||
@ -125,7 +142,6 @@ impl CdsShortTimeProvider {
|
|||||||
let unix_days_seconds = epoch - secs_of_day;
|
let unix_days_seconds = epoch - secs_of_day;
|
||||||
let ms_of_day = secs_of_day * 1000 + now.subsec_millis() as u64;
|
let ms_of_day = secs_of_day * 1000 + now.subsec_millis() as u64;
|
||||||
let provider = Self {
|
let provider = Self {
|
||||||
pfield: (Cds as u8) << 4,
|
|
||||||
ccsds_days: unix_to_ccsds_days((unix_days_seconds / SECONDS_PER_DAY as u64) as i32)
|
ccsds_days: unix_to_ccsds_days((unix_days_seconds / SECONDS_PER_DAY as u64) as i32)
|
||||||
as u16,
|
as u16,
|
||||||
ms_of_day: ms_of_day as u32,
|
ms_of_day: ms_of_day as u32,
|
||||||
@ -136,6 +152,7 @@ impl CdsShortTimeProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
|
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
||||||
pub fn update_from_now(&mut self) -> Result<(), SystemTimeError> {
|
pub fn update_from_now(&mut self) -> Result<(), SystemTimeError> {
|
||||||
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
|
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
|
||||||
let epoch = now.as_secs();
|
let epoch = now.as_secs();
|
||||||
@ -153,6 +170,7 @@ impl CdsShortTimeProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
|
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
||||||
pub fn ms_of_day_using_sysclock() -> u32 {
|
pub fn ms_of_day_using_sysclock() -> u32 {
|
||||||
Self::ms_of_day(seconds_since_epoch())
|
Self::ms_of_day(seconds_since_epoch())
|
||||||
}
|
}
|
||||||
@ -178,7 +196,11 @@ impl CdsShortTimeProvider {
|
|||||||
fn calc_date_time(&mut self, ms_since_last_second: u32) {
|
fn calc_date_time(&mut self, ms_since_last_second: u32) {
|
||||||
assert!(ms_since_last_second < 1000, "Invalid MS since last second");
|
assert!(ms_since_last_second < 1000, "Invalid MS since last second");
|
||||||
let ns_since_last_sec = ms_since_last_second * 1e6 as u32;
|
let ns_since_last_sec = ms_since_last_second * 1e6 as u32;
|
||||||
self.date_time = Some(Utc.timestamp(self.unix_seconds, ns_since_last_sec));
|
if let LocalResult::Single(val) = Utc.timestamp_opt(self.unix_seconds, ns_since_last_sec) {
|
||||||
|
self.date_time = Some(val);
|
||||||
|
} else {
|
||||||
|
self.date_time = None;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -188,19 +210,19 @@ impl CcsdsTimeProvider for CdsShortTimeProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn p_field(&self) -> (usize, [u8; 2]) {
|
fn p_field(&self) -> (usize, [u8; 2]) {
|
||||||
(1, [self.pfield, 0])
|
(1, [CDS_SHORT_P_FIELD, 0])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ccdsd_time_code(&self) -> CcsdsTimeCodes {
|
fn ccdsd_time_code(&self) -> CcsdsTimeCodes {
|
||||||
CcsdsTimeCodes::Cds
|
Cds
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unix_seconds(&self) -> i64 {
|
fn unix_seconds(&self) -> i64 {
|
||||||
self.unix_seconds
|
self.unix_seconds
|
||||||
}
|
}
|
||||||
|
|
||||||
fn date_time(&self) -> DateTime<Utc> {
|
fn date_time(&self) -> Option<DateTime<Utc>> {
|
||||||
self.date_time.expect("Invalid date time")
|
self.date_time
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -214,7 +236,7 @@ impl TimeWriter for CdsShortTimeProvider {
|
|||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
buf[0] = self.pfield;
|
buf[0] = CDS_SHORT_P_FIELD;
|
||||||
buf[1..3].copy_from_slice(self.ccsds_days.to_be_bytes().as_slice());
|
buf[1..3].copy_from_slice(self.ccsds_days.to_be_bytes().as_slice());
|
||||||
buf[3..7].copy_from_slice(self.ms_of_day.to_be_bytes().as_slice());
|
buf[3..7].copy_from_slice(self.ms_of_day.to_be_bytes().as_slice());
|
||||||
Ok(())
|
Ok(())
|
||||||
@ -235,19 +257,9 @@ impl TimeReader for CdsShortTimeProvider {
|
|||||||
match CcsdsTimeCodes::try_from(pfield >> 4 & 0b111) {
|
match CcsdsTimeCodes::try_from(pfield >> 4 & 0b111) {
|
||||||
Ok(cds_type) => match cds_type {
|
Ok(cds_type) => match cds_type {
|
||||||
Cds => (),
|
Cds => (),
|
||||||
_ => {
|
_ => return Err(TimestampError::InvalidTimeCode(Cds, cds_type as u8)),
|
||||||
return Err(TimestampError::InvalidTimeCode(
|
|
||||||
CcsdsTimeCodes::Cds,
|
|
||||||
cds_type as u8,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
_ => {
|
_ => return Err(TimestampError::InvalidTimeCode(Cds, pfield >> 4 & 0b111)),
|
||||||
return Err(TimestampError::InvalidTimeCode(
|
|
||||||
CcsdsTimeCodes::Cds,
|
|
||||||
pfield >> 4 & 0b111,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
let ccsds_days: u16 = u16::from_be_bytes(buf[1..3].try_into().unwrap());
|
let ccsds_days: u16 = u16::from_be_bytes(buf[1..3].try_into().unwrap());
|
||||||
let ms_of_day: u32 = u32::from_be_bytes(buf[3..7].try_into().unwrap());
|
let ms_of_day: u32 = u32::from_be_bytes(buf[3..7].try_into().unwrap());
|
||||||
@ -283,12 +295,9 @@ mod tests {
|
|||||||
time_stamper.unix_seconds(),
|
time_stamper.unix_seconds(),
|
||||||
(DAYS_CCSDS_TO_UNIX * SECONDS_PER_DAY as i32) as i64
|
(DAYS_CCSDS_TO_UNIX * SECONDS_PER_DAY as i32) as i64
|
||||||
);
|
);
|
||||||
assert_eq!(time_stamper.ccdsd_time_code(), CcsdsTimeCodes::Cds);
|
assert_eq!(time_stamper.ccdsd_time_code(), Cds);
|
||||||
assert_eq!(
|
assert_eq!(time_stamper.p_field(), (1, [(Cds as u8) << 4, 0]));
|
||||||
time_stamper.p_field(),
|
let date_time = time_stamper.date_time().unwrap();
|
||||||
(1, [(CcsdsTimeCodes::Cds as u8) << 4, 0])
|
|
||||||
);
|
|
||||||
let date_time = time_stamper.date_time();
|
|
||||||
assert_eq!(date_time.year(), 1958);
|
assert_eq!(date_time.year(), 1958);
|
||||||
assert_eq!(date_time.month(), 1);
|
assert_eq!(date_time.month(), 1);
|
||||||
assert_eq!(date_time.day(), 1);
|
assert_eq!(date_time.day(), 1);
|
||||||
@ -301,7 +310,7 @@ mod tests {
|
|||||||
fn test_time_stamp_unix_epoch() {
|
fn test_time_stamp_unix_epoch() {
|
||||||
let time_stamper = CdsShortTimeProvider::new((-DAYS_CCSDS_TO_UNIX) as u16, 0);
|
let time_stamper = CdsShortTimeProvider::new((-DAYS_CCSDS_TO_UNIX) as u16, 0);
|
||||||
assert_eq!(time_stamper.unix_seconds(), 0);
|
assert_eq!(time_stamper.unix_seconds(), 0);
|
||||||
let date_time = time_stamper.date_time();
|
let date_time = time_stamper.date_time().unwrap();
|
||||||
assert_eq!(date_time.year(), 1970);
|
assert_eq!(date_time.year(), 1970);
|
||||||
assert_eq!(date_time.month(), 1);
|
assert_eq!(date_time.month(), 1);
|
||||||
assert_eq!(date_time.day(), 1);
|
assert_eq!(date_time.day(), 1);
|
||||||
@ -392,7 +401,7 @@ mod tests {
|
|||||||
let err = res.unwrap_err();
|
let err = res.unwrap_err();
|
||||||
match err {
|
match err {
|
||||||
InvalidTimeCode(code, raw) => {
|
InvalidTimeCode(code, raw) => {
|
||||||
assert_eq!(code, CcsdsTimeCodes::Cds);
|
assert_eq!(code, Cds);
|
||||||
assert_eq!(raw, 0);
|
assert_eq!(raw, 0);
|
||||||
}
|
}
|
||||||
OtherPacketError(_) => {}
|
OtherPacketError(_) => {}
|
||||||
@ -425,7 +434,7 @@ mod tests {
|
|||||||
fn test_time_now() {
|
fn test_time_now() {
|
||||||
let timestamp_now = CdsShortTimeProvider::from_now().unwrap();
|
let timestamp_now = CdsShortTimeProvider::from_now().unwrap();
|
||||||
let compare_stamp = Utc::now();
|
let compare_stamp = Utc::now();
|
||||||
let dt = timestamp_now.date_time();
|
let dt = timestamp_now.date_time().unwrap();
|
||||||
if compare_stamp.year() > dt.year() {
|
if compare_stamp.year() > dt.year() {
|
||||||
assert_eq!(compare_stamp.year() - dt.year(), 1);
|
assert_eq!(compare_stamp.year() - dt.year(), 1);
|
||||||
} else {
|
} else {
|
||||||
|
33
src/tm.rs
33
src/tm.rs
@ -314,23 +314,22 @@ impl<'slice> PusTm<'slice> {
|
|||||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||||
let total_size = self.len_packed();
|
let total_size = self.len_packed();
|
||||||
if total_size > slice.len() {
|
if total_size > slice.len() {
|
||||||
return Err(PusError::PacketError(ByteConversionError::ToSliceTooSmall(
|
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||||
SizeMissmatch {
|
found: slice.len(),
|
||||||
found: slice.len(),
|
expected: total_size,
|
||||||
expected: total_size,
|
})
|
||||||
},
|
.into());
|
||||||
)));
|
|
||||||
}
|
}
|
||||||
sph_zc
|
sph_zc
|
||||||
.to_bytes(&mut slice[curr_idx..curr_idx + CCSDS_HEADER_LEN])
|
.to_bytes(&mut slice[curr_idx..curr_idx + CCSDS_HEADER_LEN])
|
||||||
.ok_or(PusError::PacketError(ByteConversionError::ZeroCopyToError))?;
|
.ok_or(ByteConversionError::ZeroCopyToError)?;
|
||||||
|
|
||||||
curr_idx += CCSDS_HEADER_LEN;
|
curr_idx += CCSDS_HEADER_LEN;
|
||||||
let sec_header_len = size_of::<zc::PusTmSecHeaderWithoutTimestamp>();
|
let sec_header_len = size_of::<zc::PusTmSecHeaderWithoutTimestamp>();
|
||||||
let sec_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
|
let sec_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
|
||||||
sec_header
|
sec_header
|
||||||
.write_to_bytes(&mut slice[curr_idx..curr_idx + sec_header_len])
|
.write_to_bytes(&mut slice[curr_idx..curr_idx + sec_header_len])
|
||||||
.ok_or(PusError::PacketError(ByteConversionError::ZeroCopyToError))?;
|
.ok_or(ByteConversionError::ZeroCopyToError)?;
|
||||||
curr_idx += sec_header_len;
|
curr_idx += sec_header_len;
|
||||||
let timestamp_len = self.sec_header.time_stamp.len();
|
let timestamp_len = self.sec_header.time_stamp.len();
|
||||||
slice[curr_idx..curr_idx + timestamp_len].copy_from_slice(self.sec_header.time_stamp);
|
slice[curr_idx..curr_idx + timestamp_len].copy_from_slice(self.sec_header.time_stamp);
|
||||||
@ -353,6 +352,7 @@ impl<'slice> PusTm<'slice> {
|
|||||||
|
|
||||||
/// Append the raw PUS byte representation to a provided [alloc::vec::Vec]
|
/// Append the raw PUS byte representation to a provided [alloc::vec::Vec]
|
||||||
#[cfg(feature = "alloc")]
|
#[cfg(feature = "alloc")]
|
||||||
|
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
||||||
pub fn append_to_vec(&self, vec: &mut Vec<u8>) -> Result<usize, PusError> {
|
pub fn append_to_vec(&self, vec: &mut Vec<u8>) -> Result<usize, PusError> {
|
||||||
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
|
||||||
let mut appended_len =
|
let mut appended_len =
|
||||||
@ -388,7 +388,7 @@ impl<'slice> PusTm<'slice> {
|
|||||||
/// Create a [PusTm] instance from a raw slice. On success, it returns a tuple containing
|
/// 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
|
/// the instance and the found byte length of the packet. The timestamp length needs to be
|
||||||
/// known beforehand.
|
/// known beforehand.
|
||||||
pub fn new_from_raw_slice(
|
pub fn from_bytes(
|
||||||
slice: &'slice [u8],
|
slice: &'slice [u8],
|
||||||
timestamp_len: usize,
|
timestamp_len: usize,
|
||||||
) -> Result<(Self, usize), PusError> {
|
) -> Result<(Self, usize), PusError> {
|
||||||
@ -399,9 +399,7 @@ impl<'slice> PusTm<'slice> {
|
|||||||
let mut current_idx = 0;
|
let mut current_idx = 0;
|
||||||
let sph =
|
let sph =
|
||||||
crate::zc::SpHeader::from_bytes(&slice[current_idx..current_idx + CCSDS_HEADER_LEN])
|
crate::zc::SpHeader::from_bytes(&slice[current_idx..current_idx + CCSDS_HEADER_LEN])
|
||||||
.ok_or(PusError::PacketError(
|
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||||
ByteConversionError::ZeroCopyFromError,
|
|
||||||
))?;
|
|
||||||
current_idx += 6;
|
current_idx += 6;
|
||||||
let total_len = sph.total_len();
|
let total_len = sph.total_len();
|
||||||
if raw_data_len < total_len || total_len < PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA {
|
if raw_data_len < total_len || total_len < PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA {
|
||||||
@ -410,9 +408,7 @@ impl<'slice> PusTm<'slice> {
|
|||||||
let sec_header_zc = zc::PusTmSecHeaderWithoutTimestamp::from_bytes(
|
let sec_header_zc = zc::PusTmSecHeaderWithoutTimestamp::from_bytes(
|
||||||
&slice[current_idx..current_idx + PUC_TM_MIN_SEC_HEADER_LEN],
|
&slice[current_idx..current_idx + PUC_TM_MIN_SEC_HEADER_LEN],
|
||||||
)
|
)
|
||||||
.ok_or(PusError::PacketError(
|
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||||
ByteConversionError::ZeroCopyFromError,
|
|
||||||
))?;
|
|
||||||
current_idx += PUC_TM_MIN_SEC_HEADER_LEN;
|
current_idx += PUC_TM_MIN_SEC_HEADER_LEN;
|
||||||
let zc_sec_header_wrapper = zc::PusTmSecHeader {
|
let zc_sec_header_wrapper = zc::PusTmSecHeader {
|
||||||
zc_header: sec_header_zc,
|
zc_header: sec_header_zc,
|
||||||
@ -545,8 +541,7 @@ mod tests {
|
|||||||
.write_to_bytes(&mut buf)
|
.write_to_bytes(&mut buf)
|
||||||
.expect("Serialization failed");
|
.expect("Serialization failed");
|
||||||
assert_eq!(ser_len, 22);
|
assert_eq!(ser_len, 22);
|
||||||
let (tm_deserialized, size) =
|
let (tm_deserialized, size) = PusTm::from_bytes(&buf, 7).expect("Deserialization failed");
|
||||||
PusTm::new_from_raw_slice(&buf, 7).expect("Deserialization failed");
|
|
||||||
assert_eq!(ser_len, size);
|
assert_eq!(ser_len, size);
|
||||||
verify_ping_reply(&tm_deserialized, false, 22, dummy_time_stamp());
|
verify_ping_reply(&tm_deserialized, false, 22, dummy_time_stamp());
|
||||||
}
|
}
|
||||||
@ -580,9 +575,9 @@ mod tests {
|
|||||||
let res = pus_tm.write_to_bytes(&mut buf);
|
let res = pus_tm.write_to_bytes(&mut buf);
|
||||||
assert!(res.is_err());
|
assert!(res.is_err());
|
||||||
let error = res.unwrap_err();
|
let error = res.unwrap_err();
|
||||||
assert!(matches!(error, PusError::PacketError { .. }));
|
assert!(matches!(error, PusError::ByteConversionError { .. }));
|
||||||
match error {
|
match error {
|
||||||
PusError::PacketError(err) => match err {
|
PusError::ByteConversionError(err) => match err {
|
||||||
ByteConversionError::ToSliceTooSmall(size_missmatch) => {
|
ByteConversionError::ToSliceTooSmall(size_missmatch) => {
|
||||||
assert_eq!(size_missmatch.expected, 22);
|
assert_eq!(size_missmatch.expected, 22);
|
||||||
assert_eq!(size_missmatch.found, 16);
|
assert_eq!(size_missmatch.found, 16);
|
||||||
|
Reference in New Issue
Block a user