61 Commits

Author SHA1 Message Date
d972dd5223 cargo fmt
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2023-01-10 16:59:13 +01:00
481de83fdb move lifetime docs further up
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2023-01-10 16:20:50 +01:00
09b305f529 better names for lifetimes
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2023-01-10 16:19:21 +01:00
78c5787e07 add some more basic docs
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2023-01-10 16:12:20 +01:00
e9e33b0335 release this tomorrow
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2023-01-10 00:00:10 +01:00
455be77f4a more docs 2023-01-09 23:59:55 +01:00
c748657499 allow minor release bump for serde and crc dependency
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2023-01-09 23:49:17 +01:00
2e90cba5bd put some ASCII includes behind alloc feature
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2023-01-09 23:47:47 +01:00
f290d2a54e re-remove Default impl for CDS time provider
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2023-01-09 23:46:31 +01:00
da695e4705 v0.4.0 preparation
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2023-01-09 11:21:07 +01:00
5c222735d4 Merge branch 'main' of https://egit.irs.uni-stuttgart.de/rust/spacepackets
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2023-01-09 11:19:16 +01:00
1432c298b3 feature list update 2023-01-09 11:19:10 +01:00
1b45082ace Merge pull request 'Add CUC impl' (#4) from add_cuc_time_impl into main
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Reviewed-on: #4
Reviewed-by: Paul Nehlich <nehlichp@irs.uni-stuttgart.de>
2023-01-09 11:14:40 +01:00
4c20158dcc Merge branch 'main' into add_cuc_time_impl
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2023-01-09 11:12:47 +01:00
c879181093 update changelog
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2023-01-09 11:12:07 +01:00
6c88e94742 Merge remote-tracking branch 'origin/main' into add_cuc_time_impl
Some checks failed
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main There was a failure building this commit
2023-01-09 11:10:44 +01:00
3fb2fbd20c Merge pull request 'Improve CDS timecode implementation' (#3) from improve_cds_short_impl into main
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Reviewed-on: #3
2023-01-09 11:08:11 +01:00
ec8a2e1d24 rename pfield preamble constant, add for CUC
Some checks failed
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main There was a failure building this commit
2023-01-09 11:07:43 +01:00
192e2f2c76 make pfield public
All checks were successful
Rust/spacepackets/pipeline/pr-main This commit looks good
Rust/spacepackets/pipeline/head This commit looks good
2023-01-09 11:06:51 +01:00
5df221759f conversion from now bugfix
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-22 23:55:05 +01:00
f137bd2549 improve tests
All checks were successful
Rust/spacepackets/pipeline/pr-main This commit looks good
Rust/spacepackets/pipeline/head This commit looks good
2022-12-22 23:45:15 +01:00
630bffec51 Merge branch 'main' into improve_cds_short_impl
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-22 23:12:35 +01:00
a14ae37cac Merge pull request 'added sp header getter function' (#6) from sp_header_getter into main
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Reviewed-on: #6
2022-12-22 09:06:33 +01:00
2758699601 added sp header getter function
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2022-12-21 22:09:45 +01:00
b07cec28ea update changelog
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-21 10:14:58 +01:00
51963d0f72 remove default impl for cds TimeProvider 2022-12-21 10:14:13 +01:00
83e2cad753 cargo fmt
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-21 09:47:09 +01:00
472bfa9964 add floating point division code
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-21 01:17:36 +01:00
14fa1bad92 add TODO
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-21 01:03:26 +01:00
3828a98c76 important bugfix
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-21 01:01:05 +01:00
f641248ac2 add PR link
Some checks failed
Rust/spacepackets/pipeline/head There was a failure building this commit
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-20 16:28:10 +01:00
884de647ad add PR link
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-20 16:27:23 +01:00
0d8074c6b9 clippy fixes
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-20 16:26:04 +01:00
6798e3a6f5 Merge remote-tracking branch 'origin/main' into improve_cds_short_impl
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-20 16:23:24 +01:00
7e763fe055 Merge remote-tracking branch 'origin/main' into add_cuc_time_impl
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-20 16:22:23 +01:00
4410ee7eec bump changelog
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2022-12-20 16:21:30 +01:00
2895d7645a Merge pull request 'PTC and PFC extensions' (#5) from ptc_pfc_extension into main
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Reviewed-on: #5
2022-12-20 16:19:21 +01:00
692d12e5a5 Merge branch 'main' into ptc_pfc_extension
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-20 16:15:46 +01:00
9e57ce3872 cargo fmt
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2022-12-19 17:02:19 +01:00
fd13694904 add PUS service ID enum
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2022-12-19 16:36:18 +01:00
976fe9c49b README updates
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2022-12-19 11:02:36 +01:00
fbeea41e8f fix in Cargo.toml file 2022-12-19 11:00:45 +01:00
177ddba9c5 clippy fixes
Some checks failed
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main There was a failure building this commit
2022-12-19 00:01:07 +01:00
f964342556 removed unnecessary casts
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2022-12-18 23:54:13 +01:00
46e2af41d2 PTC and PFC extensions
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
- Add Ptc typedefinition for PacketTypeCode enum
- Add `UnsignedPfc` and `RealPfc` PFC enumerations
2022-12-18 16:21:20 +01:00
fc05eaa925 Merge remote-tracking branch 'origin/main' into add_cuc_time_impl
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-12 11:57:00 +01:00
5a878ef6a3 Merge remote-tracking branch 'origin/main' into improve_cds_short_impl
Some checks failed
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main There was a failure building this commit
2022-12-12 11:56:08 +01:00
66d77fda36 Merge pull request 'Add Error impls if std feature is used' (#2) from add_error_impls_for_std_feature into main
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Reviewed-on: #2
2022-12-12 11:54:51 +01:00
ef963187ac update changelog
Some checks failed
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main There was a failure building this commit
2022-12-10 18:27:13 +01:00
93159dae45 some more docs
All checks were successful
Rust/spacepackets/pipeline/pr-main This commit looks good
Rust/spacepackets/pipeline/head This commit looks good
2022-12-10 18:23:47 +01:00
f73edd71fd better structure
All checks were successful
Rust/spacepackets/pipeline/pr-main This commit looks good
Rust/spacepackets/pipeline/head This commit looks good
2022-12-10 18:18:41 +01:00
6341cf35d3 added doc test / example as well
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-10 18:09:00 +01:00
1d9329ad63 this should cover most basic cases
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-10 17:39:15 +01:00
d889826b79 remove duplicate function
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-10 16:42:24 +01:00
e155ddbcb0 add more tests and additional check
All checks were successful
Rust/spacepackets/pipeline/pr-main This commit looks good
Rust/spacepackets/pipeline/head This commit looks good
2022-12-10 16:35:00 +01:00
7615e40e43 basic docs
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-09 17:33:04 +01:00
bccbdf65a3 basic impl done, add first unittests
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-09 17:21:45 +01:00
8d0de0dce4 continued cuc impl 2022-12-09 16:51:48 +01:00
5958d19eb4 continue cuc impl
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2022-12-09 13:50:04 +01:00
66b4bf6013 Merge remote-tracking branch 'origin/main' into add_error_impls_for_std_feature
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main This commit looks good
2022-12-07 19:05:55 +01:00
afd59b14fc Merge remote-tracking branch 'origin/main' into add_error_impls_for_std_feature
Some checks failed
Rust/spacepackets/pipeline/head This commit looks good
Rust/spacepackets/pipeline/pr-main There was a failure building this commit
2022-12-07 18:43:56 +01:00
11 changed files with 888 additions and 128 deletions

View File

@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
# [unreleased]
# [v0.4.0] 10.01.2023
## Fixed
- Remove `Default` derive on CDS time provider. This can lead to uninitialized preamble fields.
## Changed
- `serde` support is now optional and behind the `serde` feature.
@ -19,11 +25,18 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
The function now returns the remaining slice as well.
- All CDS specific functionality was moved into the `cds` submodule of the `time`
module. `CdsShortTimeProvider` was renamed to `TimeProvider`.
PR: https://egit.irs.uni-stuttgart.de/rust/spacepackets/pulls/3
## Added
- `SpHeader` getter function `sp_header` added for `PusTc`
PR: https://egit.irs.uni-stuttgart.de/rust/spacepackets/pulls/6
- Added PFC enumerations: `ecss::UnsignedPfc` and `ecss::RealPfc`.
PR: https://egit.irs.uni-stuttgart.de/rust/spacepackets/pulls/5
- Added `std::error::Error` implementation for all error enumerations if the `std` feature
is enabled.
- CUC timestamp implementation as specified in CCSDS 301.0-B-4 section 3.2.
PR: https://egit.irs.uni-stuttgart.de/rust/spacepackets/pulls/4/files
- ACII timestamps as specified in CCSDS 301.0-B-4 section 3.5.
- Added MSRV in `Cargo.toml` with the `rust-version` field set to Rust 1.60.
- `serde` `Serialize` and `Deserialize` added to all types.

View File

@ -1,6 +1,6 @@
[package]
name = "spacepackets"
version = "0.3.1"
version = "0.4.0"
edition = "2021"
rust-version = "1.60"
authors = ["Robin Mueller <muellerr@irs.uni-stuttgart.de>"]
@ -14,11 +14,11 @@ categories = ["aerospace", "aerospace::space-protocols", "no-std", "hardware-sup
[dependencies]
zerocopy = "0.6"
crc = "3.0"
crc = "3"
delegate = "0.8"
[dependencies.serde]
version = "1.0"
version = "1"
optional = true
default-features = false
features = ["derive"]
@ -35,9 +35,9 @@ default-features = false
version = "1.0"
[features]
default = ["std", "dep:serde"]
default = ["std"]
std = ["chrono/std", "chrono/clock", "alloc"]
serde = ["chrono/serde"]
serde = ["dep:serde", "chrono/serde"]
alloc = ["postcard/alloc", "chrono/alloc"]
[package.metadata.docs.rs]

View File

@ -15,7 +15,9 @@ Currently, this includes the following components:
[CCSDS Blue Book 133.0-B-2](https://public.ccsds.org/Pubs/133x0b2e1.pdf)
- PUS Telecommand and PUS Telemetry implementation according to the
[ECSS-E-ST-70-41C standard](https://ecss.nl/standard/ecss-e-st-70-41c-space-engineering-telemetry-and-telecommand-packet-utilization-15-april-2016/).
- CDS Short Time Code implementation according to
- CUC (CCSDS Unsegmented Time Code) implementation according to
[CCSDS 301.0-B-4 3.2](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
- CDS (CCSDS Day Segmented Time Code) implementation according to
[CCSDS 301.0-B-4 3.3](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
- Some helper types to support ASCII timecodes ad specified in
[CCSDS 301.0-B-4 3.5](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
@ -28,12 +30,15 @@ It also offers optional support for [`serde`](https://serde.rs/). This allows se
deserializing them with an appropriate `serde` provider like
[`postcard`](https://github.com/jamesmunns/postcard).
Default features:
## Default features
- [`std`](https://doc.rust-lang.org/std/): Enables functionality relying on the standard library.
- [`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).
Enabled by the `std` feature.
## Optional Features
- [`serde`](https://serde.rs/): Adds `serde` support for most types by adding `Serialize` and `Deserialize` `derive`s
# Examples

View File

@ -15,6 +15,21 @@ pub type CrcType = u16;
pub const CRC_CCITT_FALSE: Crc<u16> = Crc::<u16>::new(&CRC_16_IBM_3740);
pub const CCSDS_HEADER_LEN: usize = size_of::<crate::zc::SpHeader>();
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum PusServiceId {
/// Service 1
Verification = 1,
/// Service 3
Housekeeping = 3,
/// Service 5
Event = 5,
/// Service 8
Action = 8,
/// Service 17
Test = 17,
}
/// All PUS versions. Only PUS C is supported by this library.
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
@ -38,6 +53,7 @@ impl TryFrom<u8> for PusVersion {
}
}
/// ECSS Packet Type Codes (PTC)s.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum PacketTypeCodes {
@ -55,6 +71,38 @@ pub enum PacketTypeCodes {
Packet = 12,
}
pub type Ptc = PacketTypeCodes;
/// ECSS Packet Field Codes (PFC)s for the unsigned [Ptc].
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum UnsignedPfc {
OneByte = 4,
TwelveBits = 8,
TwoBytes = 12,
ThreeBytes = 13,
FourBytes = 14,
SixBytes = 15,
EightBytes = 16,
OneBit = 17,
TwoBits = 18,
ThreeBits = 19,
}
/// ECSS Packet Field Codes (PFC)s for the real (floating point) [Ptc].
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum RealPfc {
/// 4 octets simple precision format (IEEE)
Float = 1,
/// 8 octets simple precision format (IEEE)
Double = 2,
/// 4 octets simple precision format (MIL-STD)
FloatMilStd = 3,
/// 8 octets simple precision format (MIL-STD)
DoubleMilStd = 4,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum PusError {
@ -112,6 +160,8 @@ impl From<ByteConversionError> for PusError {
}
}
/// Generic trait to describe common attributes for both PUS Telecommands (TC) and PUS Telemetry
/// (TM) packets. All PUS packets are also a special type of [CcsdsPacket]s.
pub trait PusPacket: CcsdsPacket {
const PUS_VERSION: PusVersion = PusVersion::PusC;
@ -286,13 +336,13 @@ impl<TYPE: ToBeBytes> EcssEnumeration for GenericEcssEnumWrapper<TYPE> {
}
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() {
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
found: buf.len(),
expected: self.byte_width() as usize,
expected: self.byte_width(),
}));
}
buf[0..self.byte_width() as usize].copy_from_slice(self.val.to_be_bytes().as_ref());
buf[0..self.byte_width()].copy_from_slice(self.val.to_be_bytes().as_ref());
Ok(())
}
}

View File

@ -9,9 +9,11 @@
//! [CCSDS Blue Book 133.0-B-2](https://public.ccsds.org/Pubs/133x0b2e1.pdf)
//! - PUS Telecommand and PUS Telemetry implementation according to the
//! [ECSS-E-ST-70-41C standard](https://ecss.nl/standard/ecss-e-st-70-41c-space-engineering-telemetry-and-telecommand-packet-utilization-15-april-2016/).
//! - CDS Short Time Code implementation according to
//! [CCSDS CCSDS 301.0-B-4](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
//! - Some helper types and functions to support ASCII timecodes ad specified in
//! - CUC (CCSDS Unsegmented Time Code) implementation according to
//! [CCSDS 301.0-B-4 3.2](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
//! - CDS (CCSDS Day Segmented Time Code) implementation according to
//! [CCSDS 301.0-B-4 3.3](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
//! - Some helper types to support ASCII timecodes ad specified in
//! [CCSDS 301.0-B-4 3.5](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
//!
//! ## Features
@ -22,12 +24,15 @@
//! deserializing them with an appropriate `serde` provider like
//! [`postcard`](https://github.com/jamesmunns/postcard).
//!
//! Default features:
//! ### Default features
//!
//! - [`std`](https://doc.rust-lang.org/std/): Enables functionality relying on the standard library.
//! - [`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).
//! Enabled by the `std` feature.
//!
//! ### Optional features
//!
//! - [`serde`](https://serde.rs/): Adds `serde` support for most types by adding `Serialize` and
//! `Deserialize` `derive`s
//!
@ -124,6 +129,7 @@ impl Display for ByteConversionError {
#[cfg(feature = "std")]
impl Error for ByteConversionError {}
/// CCSDS packet type enumeration.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum PacketType {
@ -172,6 +178,8 @@ impl TryFrom<u8> for SequenceFlags {
}
}
/// Abstraction for the CCSDS Packet ID, which forms the last thirteen bits
/// of the first two bytes in the CCSDS primary header.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PacketId {
@ -255,6 +263,8 @@ impl From<u16> for PacketId {
}
}
/// Abstraction for the CCSDS Packet Sequence Control (PSC) field which is the
/// third and the fourth byte in the CCSDS primary header.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PacketSequenceCtrl {

View File

@ -215,19 +215,19 @@ impl PusTcSecondaryHeader {
/// There is no spare bytes support yet.
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PusTc<'slice> {
pub struct PusTc<'app_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<&'slice [u8]>,
app_data: Option<&'slice [u8]>,
raw_data: Option<&'app_data [u8]>,
app_data: Option<&'app_data [u8]>,
crc16: Option<u16>,
}
impl<'slice> PusTc<'slice> {
impl<'app_data> PusTc<'app_data> {
/// Generates a new struct instance.
///
/// # Arguments
@ -243,7 +243,7 @@ impl<'slice> PusTc<'slice> {
pub fn new(
sp_header: &mut SpHeader,
sec_header: PusTcSecondaryHeader,
app_data: Option<&'slice [u8]>,
app_data: Option<&'app_data [u8]>,
set_ccsds_len: bool,
) -> Self {
sp_header.set_packet_type(PacketType::Tc);
@ -268,7 +268,7 @@ impl<'slice> PusTc<'slice> {
sph: &mut SpHeader,
service: u8,
subservice: u8,
app_data: Option<&'slice [u8]>,
app_data: Option<&'app_data [u8]>,
set_ccsds_len: bool,
) -> Self {
Self::new(
@ -279,6 +279,10 @@ impl<'slice> PusTc<'slice> {
)
}
pub fn sp_header(&self) -> &SpHeader {
&self.sp_header
}
pub fn len_packed(&self) -> usize {
let mut length = PUS_TC_MIN_LEN_WITHOUT_APP_DATA;
if let Some(app_data) = self.app_data {
@ -401,7 +405,7 @@ impl<'slice> PusTc<'slice> {
/// 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.
pub fn from_bytes(slice: &'slice [u8]) -> Result<(Self, usize), PusError> {
pub fn from_bytes(slice: &'app_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));
@ -431,7 +435,7 @@ impl<'slice> PusTc<'slice> {
Ok((pus_tc, total_len))
}
pub fn raw(&self) -> Option<&'slice [u8]> {
pub fn raw(&self) -> Option<&'app_data [u8]> {
self.raw_data
}
}

View File

@ -3,8 +3,10 @@
//! See [chrono::DateTime::format] for a usage example of the generated
//! [chrono::format::DelayedFormat] structs.
#[cfg(feature = "alloc")]
use chrono::format::{DelayedFormat, StrftimeItems};
use chrono::{DateTime, Utc};
use chrono::{
format::{DelayedFormat, StrftimeItems},
DateTime, Utc,
};
/// Tuple of format string and formatted size for time code A.
///

View File

@ -1,4 +1,4 @@
//! Module to generate or read CDS timestamps as specified in
//! Module to generate or read CCSDS Day Segmented (CDS) timestamps as specified in
//! [CCSDS 301.0-B-4](https://public.ccsds.org/Pubs/301x0b4e1.pdf) section 3.3 .
//!
//! The core data structure to do this is the [cds::TimeProvider] struct.
@ -6,7 +6,8 @@ use super::*;
use crate::private::Sealed;
use core::fmt::Debug;
const CDS_SHORT_P_FIELD: u8 = (CcsdsTimeCodes::Cds as u8) << 4;
/// Base value for the preamble field for a time field parser to determine the time field type.
pub const P_FIELD_BASE: u8 = (CcsdsTimeCodes::Cds as u8) << 4;
pub const MIN_CDS_FIELD_LEN: usize = 7;
/// Generic trait implemented by token structs to specify the length of day field at type
@ -124,7 +125,7 @@ pub fn precision_from_pfield(pfield: u8) -> SubmillisPrecision {
/// assert_eq!(stamp_deserialized.len_as_bytes(), 7);
/// }
/// ```
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TimeProvider<DaysLen: ProvidesDaysLength = DaysLen16Bits> {
pfield: u8,
@ -338,9 +339,8 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
unix_seconds: 0,
submillis_precision: None,
};
let unix_days_seconds =
ccsds_to_unix_days(ccsds_days.into()) as i64 * SECONDS_PER_DAY as i64;
provider.setup(unix_days_seconds as i64, ms_of_day.into());
let unix_days_seconds = ccsds_to_unix_days(ccsds_days.into()) * SECONDS_PER_DAY as i64;
provider.setup(unix_days_seconds, ms_of_day.into());
Ok(provider)
}
@ -392,7 +392,7 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
day_seg_len: LengthOfDaySegment,
submillis_prec: Option<SubmillisPrecision>,
) -> u8 {
let mut pfield = CDS_SHORT_P_FIELD | ((day_seg_len as u8) << 2);
let mut pfield = P_FIELD_BASE | ((day_seg_len as u8) << 2);
if let Some(submillis_prec) = submillis_prec {
match submillis_prec {
SubmillisPrecision::Microseconds(_) => pfield |= 0b01,
@ -552,7 +552,7 @@ impl<ProvidesDaysLen: ProvidesDaysLength> CcsdsTimeProvider for TimeProvider<Pro
}
fn date_time(&self) -> Option<DateTime<Utc>> {
self.calc_date_time((self.ms_of_day % 1000) as u32)
self.calc_date_time(self.ms_of_day % 1000)
}
}

View File

@ -1,15 +1,96 @@
//! Module to generate or read CCSDS Unsegmented (CUC) timestamps as specified in
//! [CCSDS 301.0-B-4](https://public.ccsds.org/Pubs/301x0b4e1.pdf) section 3.2 .
//!
//! The core data structure to do this is the [TimeProviderCcsdsEpoch] struct.
use super::*;
use core::fmt::Debug;
const MIN_CUC_LEN: usize = 2;
/// Base value for the preamble field for a time field parser to determine the time field type.
pub const P_FIELD_BASE: u8 = (CcsdsTimeCodes::CucCcsdsEpoch as u8) << 4;
/// Maximum length if the preamble field is not extended.
pub const MAX_CUC_LEN_SMALL_PREAMBLE: usize = 8;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum FractionalResolution {
/// No fractional part, only second resolution
Seconds = 0,
/// 256 fractional parts, resulting in 1/255 ~= 4 ms fractional resolution
FourMs = 1,
/// 65535 fractional parts, resulting in 1/65535 ~= 15 us fractional resolution
FifteenUs = 2,
/// 16777215 fractional parts, resulting in 1/16777215 ~= 60 ns fractional resolution
SixtyNs = 3,
}
impl TryFrom<u8> for FractionalResolution {
type Error = ();
fn try_from(v: u8) -> Result<Self, Self::Error> {
match v {
0 => Ok(FractionalResolution::Seconds),
1 => Ok(FractionalResolution::FourMs),
2 => Ok(FractionalResolution::FifteenUs),
3 => Ok(FractionalResolution::SixtyNs),
_ => Err(()),
}
}
}
/// Please note that this function will panic if the fractional value is not smaller than
/// the maximum number of fractions allowed for the particular resolution.
/// (e.g. passing 270 when the resolution only allows 255 values).
pub fn convert_fractional_part_to_ns(fractional_part: FractionalPart) -> u64 {
let div = fractional_res_to_div(fractional_part.0);
assert!(fractional_part.1 < div);
10_u64.pow(9) * fractional_part.1 as u64 / div as u64
}
pub const fn fractional_res_to_div(res: FractionalResolution) -> u32 {
2_u32.pow(8 * res as u32) - 1
}
/// Calculate the fractional part for a given resolution and subsecond nanoseconds.
/// Please note that this function will panic if the passed nanoseconds exceeds 1 second
/// as a nanosecond (10 to the power of 9). Furthermore, it will return [None] if the
/// given resolution is [FractionalResolution::Seconds].
pub fn fractional_part_from_subsec_ns(
res: FractionalResolution,
ns: u64,
) -> Option<FractionalPart> {
if res == FractionalResolution::Seconds {
return None;
}
let sec_as_ns = 10_u64.pow(9);
if ns > sec_as_ns {
panic!("passed nanosecond value larger than 1 second");
}
let resolution = fractional_res_to_div(res) as u64;
// Use integer division because this can reduce code size of really small systems.
// First determine the nanoseconds for the smallest segment given the resolution.
// Then divide by that to find out the fractional part. For the calculation of the smallest
// fraction, we perform a ceiling division. This is because if we would use the default
// flooring division, we would divide by a smaller value, thereby allowing the calculation to
// invalid fractional parts which are too large. For the division of the nanoseconds by the
// smallest fraction, a flooring division is correct.
// The multiplication with 100000 is necessary to avoid precision loss during integer division.
// TODO: Floating point division might actually be faster option, but requires additional
// code on small embedded systems..
let fractional_part = ns * 100000 / ((sec_as_ns * 100000 + resolution) / resolution);
// Floating point division.
//let fractional_part = (ns as f64 / ((sec_as_ns as f64) / resolution as f64)).floor() as u32;
Some(FractionalPart(res, fractional_part as u32))
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CucError {
InvalidCounterWidth(u8),
InvalidFractionWidth(u8),
InvalidFractionResolution(FractionalResolution),
InvalidCounter(u8, u64),
InvalidFractions(u8, u64),
InvalidFractions(FractionalResolution, u64),
}
impl Display for CucError {
@ -18,14 +99,14 @@ impl Display for CucError {
CucError::InvalidCounterWidth(w) => {
write!(f, "invalid cuc counter byte width {}", w)
}
CucError::InvalidFractionWidth(w) => {
write!(f, "invalid cuc fractional part byte width {}", w)
CucError::InvalidFractionResolution(w) => {
write!(f, "invalid cuc fractional part byte width {:?}", w)
}
CucError::InvalidCounter(w, c) => {
write!(f, "invalid cuc counter {} for width {}", c, w)
}
CucError::InvalidFractions(w, c) => {
write!(f, "invalid cuc fractional part {} for width {}", c, w)
write!(f, "invalid cuc fractional part {} for width {:?}", c, w)
}
}
}
@ -37,18 +118,51 @@ impl Error for CucError {}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct WidthCounterPair(u8, u32);
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FractionalPart(FractionalResolution, u32);
/// This provider uses the CCSDS epoch. Furthermore the preamble field only has one byte,
/// which allows a time code representation through the year 2094.
/// This object is the abstraction for the CCSDS Unsegmented Time Code (CUC) using the CCSDS epoch
/// and a small preamble field.
///
/// More specifically, only having a preamble field of one byte limits the width of the counter
/// type (generally seconds) to 4 bytes and the width of the fractions type to 3 bytes.
/// It has the capability to generate and read timestamps as specified in the CCSDS 301.0-B-4
/// section 3.2 . The preamble field only has one byte, which allows a time code representation
/// through the year 2094. The time is represented as a simple binary counter starting from the
/// fixed CCSDS epoch (1958-01-01 00:00:00). It is possible to provide subsecond accuracy using the
/// fractional field with various available [resolutions][FractionalResolution].
///
/// Having a preamble field of one byte limits the width of the counter
/// type (generally seconds) to 4 bytes and the width of the fractions type to 3 bytes. This limits
/// the maximum time stamp size to [MAX_CUC_LEN_SMALL_PREAMBLE] (8 bytes).
///
/// # Example
///
/// ```
/// use spacepackets::time::cuc::{FractionalResolution, TimeProviderCcsdsEpoch};
/// use spacepackets::time::{TimeWriter, CcsdsTimeCodes, TimeReader, CcsdsTimeProvider};
///
/// // Highest fractional resolution
/// let timestamp_now = TimeProviderCcsdsEpoch::from_now(FractionalResolution::SixtyNs).expect("creating cuc stamp failed");
/// let mut raw_stamp = [0; 16];
/// {
/// let written = timestamp_now.write_to_bytes(&mut raw_stamp).expect("writing timestamp failed");
/// assert_eq!((raw_stamp[0] >> 4) & 0b111, CcsdsTimeCodes::CucCcsdsEpoch as u8);
/// // 1 byte preamble + 4 byte counter + 3 byte fractional part
/// assert_eq!(written, 8);
/// }
/// {
/// let read_result = TimeProviderCcsdsEpoch::from_bytes(&raw_stamp);
/// assert!(read_result.is_ok());
/// let stamp_deserialized = read_result.unwrap();
/// assert_eq!(stamp_deserialized, timestamp_now);
/// }
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TimeProviderCcsdsEpoch {
pfield: u8,
counter: WidthCounterPair,
fractions: Option<WidthCounterPair>,
fractions: Option<FractionalPart>,
}
#[inline]
@ -60,24 +174,162 @@ pub fn pfield_len(pfield: u8) -> usize {
}
impl TimeProviderCcsdsEpoch {
fn build_p_field(counter_width: u8, fractions_width: Option<u8>) -> u8 {
let mut pfield = (CcsdsTimeCodes::CucCcsdsEpoch as u8) << 4;
/// Create a time provider with a four byte counter and no fractional part.
pub fn new(counter: u32) -> Self {
// These values are definitely valid, so it is okay to unwrap here.
Self::new_generic(WidthCounterPair(4, counter), None).unwrap()
}
/// Like [TimeProviderCcsdsEpoch::new] but allow to supply a fractional part as well.
pub fn new_with_fractions(counter: u32, fractions: FractionalPart) -> Result<Self, CucError> {
Self::new_generic(WidthCounterPair(4, counter), Some(fractions))
}
/// Fractions with a resolution of ~ 4 ms
pub fn new_with_coarse_fractions(counter: u32, subsec_fractions: u8) -> Self {
// These values are definitely valid, so it is okay to unwrap here.
Self::new_generic(
WidthCounterPair(4, counter),
Some(FractionalPart(
FractionalResolution::FourMs,
subsec_fractions as u32,
)),
)
.unwrap()
}
/// Fractions with a resolution of ~ 16 us
pub fn new_with_medium_fractions(counter: u32, subsec_fractions: u16) -> Self {
// These values are definitely valid, so it is okay to unwrap here.
Self::new_generic(
WidthCounterPair(4, counter),
Some(FractionalPart(
FractionalResolution::FifteenUs,
subsec_fractions as u32,
)),
)
.unwrap()
}
/// Fractions with a resolution of ~ 60 ns. The fractional part value is limited by the
/// 24 bits of the fractional field, so this function will fail with
/// [CucError::InvalidFractions] if the fractional value exceeds the value.
pub fn new_with_fine_fractions(counter: u32, subsec_fractions: u32) -> Result<Self, CucError> {
Self::new_generic(
WidthCounterPair(4, counter),
Some(FractionalPart(
FractionalResolution::SixtyNs,
subsec_fractions,
)),
)
}
/// This function will return the current time as a CUC timestamp.
/// The counter width will always be set to 4 bytes because the normal CCSDS epoch will overflow
/// when using less than that.
#[cfg(feature = "std")]
pub fn from_now(fraction_resolution: FractionalResolution) -> Result<Self, StdTimestampError> {
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
let ccsds_epoch = unix_epoch_to_ccsds_epoch(now.as_secs());
if fraction_resolution == FractionalResolution::Seconds {
return Ok(Self::new(ccsds_epoch as u32));
}
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()))
}
/// Updates the current time stamp from the current time. The fractional field width remains
/// the same and will be updated accordingly.
#[cfg(feature = "std")]
pub fn update_from_now(&mut self) -> Result<(), StdTimestampError> {
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
self.counter.1 = unix_epoch_to_ccsds_epoch(now.as_secs()) as u32;
if self.fractions.is_some() {
self.fractions = fractional_part_from_subsec_ns(
self.fractions.unwrap().0,
now.subsec_nanos() as u64,
);
}
Ok(())
}
pub fn new_u16_counter(counter: u16) -> Self {
// These values are definitely valid, so it is okay to unwrap here.
Self::new_generic(WidthCounterPair(2, counter as u32), None).unwrap()
}
pub fn width_counter_pair(&self) -> WidthCounterPair {
self.counter
}
pub fn width_fractions_pair(&self) -> Option<FractionalPart> {
self.fractions
}
pub fn set_fractions(&mut self, fractions: FractionalPart) -> Result<(), CucError> {
Self::verify_fractions_width(fractions.0)?;
Self::verify_fractions_value(fractions)?;
self.fractions = Some(fractions);
self.update_p_field_fractions();
Ok(())
}
/// Set a fractional resolution. Please note that this function will reset the fractional value
/// to 0 if the resolution changes.
pub fn set_fractional_resolution(&mut self, res: FractionalResolution) {
if res == FractionalResolution::Seconds {
self.fractions = None;
}
let mut update_fractions = true;
if let Some(existing_fractions) = self.fractions {
if existing_fractions.0 == res {
update_fractions = false;
}
};
if update_fractions {
self.fractions = Some(FractionalPart(res, 0));
}
}
pub fn new_generic(
counter: WidthCounterPair,
fractions: Option<FractionalPart>,
) -> Result<Self, CucError> {
Self::verify_counter_width(counter.0)?;
if counter.1 > (2u64.pow(counter.0 as u32 * 8) - 1) as u32 {
return Err(CucError::InvalidCounter(counter.0, counter.1 as u64));
}
if let Some(fractions) = fractions {
Self::verify_fractions_width(fractions.0)?;
Self::verify_fractions_value(fractions)?;
}
Ok(Self {
pfield: Self::build_p_field(counter.0, fractions.map(|v| v.0)),
counter,
fractions,
})
}
fn build_p_field(counter_width: u8, fractions_width: Option<FractionalResolution>) -> u8 {
let mut pfield = P_FIELD_BASE;
if !(1..=4).contains(&counter_width) {
// Okay to panic here, this function is private and all input values should
// have been sanitized
panic!("invalid counter width {} for cuc timestamp", counter_width);
}
pfield |= (counter_width - 1) << 3;
pfield |= (counter_width - 1) << 2;
if let Some(fractions_width) = fractions_width {
if !(1..=3).contains(&fractions_width) {
if !(1..=3).contains(&(fractions_width as u8)) {
// Okay to panic here, this function is private and all input values should
// have been sanitized
panic!(
"invalid fractions width {} for cuc timestamp",
"invalid fractions width {:?} for cuc timestamp",
fractions_width
);
}
pfield |= fractions_width;
pfield |= fractions_width as u8;
}
pfield
}
@ -85,14 +337,10 @@ impl TimeProviderCcsdsEpoch {
fn update_p_field_fractions(&mut self) {
self.pfield &= !(0b11);
if let Some(fractions) = self.fractions {
self.pfield |= fractions.0;
self.pfield |= fractions.0 as u8;
}
}
pub fn len_packed(&self) -> usize {
Self::len_packed_from_pfield(self.pfield)
}
#[inline]
pub fn len_cntr_from_pfield(pfield: u8) -> u8 {
((pfield >> 2) & 0b11) + 1
@ -127,8 +375,7 @@ impl TimeProviderCcsdsEpoch {
base_len
}
/// Verifies the raw width parameter and returns the actual length, which is the raw
/// value plus 1.
/// Verifies the raw width parameter.
fn verify_counter_width(width: u8) -> Result<(), CucError> {
if width == 0 || width > 4 {
return Err(CucError::InvalidCounterWidth(width));
@ -136,14 +383,14 @@ impl TimeProviderCcsdsEpoch {
Ok(())
}
fn verify_fractions_width(width: u8) -> Result<(), CucError> {
if width > 3 {
return Err(CucError::InvalidFractionWidth(width));
fn verify_fractions_width(width: FractionalResolution) -> Result<(), CucError> {
if width as u8 > 3 {
return Err(CucError::InvalidFractionResolution(width));
}
Ok(())
}
fn verify_fractions_value(val: WidthCounterPair) -> Result<(), CucError> {
fn verify_fractions_value(val: FractionalPart) -> Result<(), CucError> {
if val.1 > 2u32.pow((val.0 as u32) * 8) - 1 {
return Err(CucError::InvalidFractions(val.0, val.1 as u64));
}
@ -151,44 +398,6 @@ impl TimeProviderCcsdsEpoch {
}
}
impl TimeProviderCcsdsEpoch {
pub fn new_default(counter: u32) -> Self {
// These values are definitely valid, so it is okay to unwrap here.
Self::new(WidthCounterPair(4, counter), None).unwrap()
}
pub fn new_u16_counter(counter: u16) -> Self {
// These values are definitely valid, so it is okay to unwrap here.
Self::new(WidthCounterPair(2, counter as u32), None).unwrap()
}
pub fn set_fractions(&mut self, fractions: WidthCounterPair) -> Result<(), CucError> {
Self::verify_fractions_width(fractions.0)?;
Self::verify_fractions_value(fractions)?;
self.fractions = Some(fractions);
self.update_p_field_fractions();
Ok(())
}
pub fn new(
counter: WidthCounterPair,
fractions: Option<WidthCounterPair>,
) -> Result<Self, CucError> {
Self::verify_counter_width(counter.0)?;
if counter.1 > 2u32.pow(counter.0 as u32 * 8) - 1 {
return Err(CucError::InvalidCounter(counter.0, counter.1 as u64));
}
if let Some(fractions) = fractions {
Self::verify_fractions_width(fractions.0)?;
Self::verify_fractions_value(fractions)?;
}
Ok(Self {
pfield: Self::build_p_field(counter.0, fractions.map(|v| v.0)),
counter,
fractions,
})
}
}
impl TimeReader for TimeProviderCcsdsEpoch {
fn from_bytes(buf: &[u8]) -> Result<Self, TimestampError>
where
@ -202,6 +411,22 @@ impl TimeReader for TimeProviderCcsdsEpoch {
}),
));
}
match ccsds_time_code_from_p_field(buf[0]) {
Ok(code) => {
if code != CcsdsTimeCodes::CucCcsdsEpoch {
return Err(TimestampError::InvalidTimeCode(
CcsdsTimeCodes::CucCcsdsEpoch,
code as u8,
));
}
}
Err(raw) => {
return Err(TimestampError::InvalidTimeCode(
CcsdsTimeCodes::CucCcsdsEpoch,
raw,
))
}
}
let (cntr_len, fractions_len, total_len) =
Self::len_components_and_total_from_pfield(buf[0]);
if buf.len() < total_len {
@ -219,19 +444,24 @@ impl TimeReader for TimeProviderCcsdsEpoch {
3 => {
let mut tmp_buf: [u8; 4] = [0; 4];
tmp_buf[1..4].copy_from_slice(&buf[current_idx..current_idx + 3]);
u32::from_be_bytes(tmp_buf) as u32
u32::from_be_bytes(tmp_buf)
}
4 => u32::from_be_bytes(buf[current_idx..current_idx + 4].try_into().unwrap()) as u32,
4 => u32::from_be_bytes(buf[current_idx..current_idx + 4].try_into().unwrap()),
_ => panic!("unreachable match arm"),
};
current_idx += cntr_len as usize;
let mut fractions = None;
if fractions_len > 0 {
match fractions_len {
1 => fractions = Some(WidthCounterPair(fractions_len, buf[current_idx] as u32)),
1 => {
fractions = Some(FractionalPart(
fractions_len.try_into().unwrap(),
buf[current_idx] as u32,
))
}
2 => {
fractions = Some(WidthCounterPair(
fractions_len,
fractions = Some(FractionalPart(
fractions_len.try_into().unwrap(),
u16::from_be_bytes(buf[current_idx..current_idx + 2].try_into().unwrap())
as u32,
))
@ -239,15 +469,15 @@ impl TimeReader for TimeProviderCcsdsEpoch {
3 => {
let mut tmp_buf: [u8; 4] = [0; 4];
tmp_buf[1..4].copy_from_slice(&buf[current_idx..current_idx + 3]);
fractions = Some(WidthCounterPair(
fractions_len,
u32::from_be_bytes(tmp_buf) as u32,
fractions = Some(FractionalPart(
fractions_len.try_into().unwrap(),
u32::from_be_bytes(tmp_buf),
))
}
_ => panic!("unreachable match arm"),
}
}
let provider = Self::new(WidthCounterPair(cntr_len, counter), fractions)?;
let provider = Self::new_generic(WidthCounterPair(cntr_len, counter), fractions)?;
Ok(provider)
}
}
@ -255,11 +485,11 @@ impl TimeReader for TimeProviderCcsdsEpoch {
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_packed() {
if bytes.len() < self.len_as_bytes() {
return Err(TimestampError::ByteConversionError(
ByteConversionError::ToSliceTooSmall(SizeMissmatch {
found: bytes.len(),
expected: self.len_packed(),
expected: self.len_as_bytes(),
}),
));
}
@ -286,10 +516,10 @@ impl TimeWriter for TimeProviderCcsdsEpoch {
current_idx += self.counter.0 as usize;
if let Some(fractions) = self.fractions {
match fractions.0 {
1 => bytes[current_idx] = fractions.1 as u8,
2 => bytes[current_idx..current_idx + 2]
FractionalResolution::FourMs => bytes[current_idx] = fractions.1 as u8,
FractionalResolution::FifteenUs => bytes[current_idx..current_idx + 2]
.copy_from_slice(&(fractions.1 as u16).to_be_bytes()),
3 => bytes[current_idx..current_idx + 3]
FractionalResolution::SixtyNs => bytes[current_idx..current_idx + 3]
.copy_from_slice(&fractions.1.to_be_bytes()[1..4]),
// Should also never happen
_ => panic!("invalid fractions value"),
@ -299,3 +529,422 @@ impl TimeWriter for TimeProviderCcsdsEpoch {
Ok(current_idx)
}
}
impl CcsdsTimeProvider for TimeProviderCcsdsEpoch {
fn len_as_bytes(&self) -> usize {
Self::len_packed_from_pfield(self.pfield)
}
fn p_field(&self) -> (usize, [u8; 2]) {
(1, [self.pfield, 0])
}
fn ccdsd_time_code(&self) -> CcsdsTimeCodes {
CcsdsTimeCodes::CucCcsdsEpoch
}
/// Please note that this function only works as intended if the time counter resolution
/// is one second.
fn unix_seconds(&self) -> i64 {
ccsds_epoch_to_unix_epoch(self.counter.1 as u64) as i64
}
fn date_time(&self) -> Option<DateTime<Utc>> {
let unix_seconds = self.unix_seconds();
let ns = if let Some(fractional_part) = self.fractions {
convert_fractional_part_to_ns(fractional_part)
} else {
0
};
if let LocalResult::Single(res) = Utc.timestamp_opt(unix_seconds, ns as u32) {
return Some(res);
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{Datelike, Timelike};
#[allow(unused_imports)]
use std::println;
#[test]
fn test_basic_zero_epoch() {
let zero_cuc = TimeProviderCcsdsEpoch::new(0);
assert_eq!(zero_cuc.len_as_bytes(), 5);
assert_eq!(zero_cuc.ccdsd_time_code(), CcsdsTimeCodes::CucCcsdsEpoch);
let counter = zero_cuc.width_counter_pair();
assert_eq!(counter.0, 4);
assert_eq!(counter.1, 0);
let fractions = zero_cuc.width_fractions_pair();
assert!(fractions.is_none());
let dt = zero_cuc.date_time();
assert!(dt.is_some());
let dt = dt.unwrap();
assert_eq!(dt.year(), 1958);
assert_eq!(dt.month(), 1);
assert_eq!(dt.day(), 1);
assert_eq!(dt.hour(), 0);
assert_eq!(dt.minute(), 0);
assert_eq!(dt.second(), 0);
}
#[test]
fn test_write_no_fractions() {
let mut buf: [u8; 16] = [0; 16];
let zero_cuc = TimeProviderCcsdsEpoch::new_generic(WidthCounterPair(4, 0x20102030), None);
assert!(zero_cuc.is_ok());
let zero_cuc = zero_cuc.unwrap();
let res = zero_cuc.write_to_bytes(&mut buf);
assert!(res.is_ok());
assert_eq!(zero_cuc.len_as_bytes(), 5);
assert_eq!(pfield_len(buf[0]), 1);
let written = res.unwrap();
assert_eq!(written, 5);
assert_eq!((buf[0] >> 7) & 0b1, 0);
let time_code = ccsds_time_code_from_p_field(buf[0]);
assert!(time_code.is_ok());
assert_eq!(time_code.unwrap(), CcsdsTimeCodes::CucCcsdsEpoch);
assert_eq!((buf[0] >> 2) & 0b11, 0b11);
assert_eq!(buf[0] & 0b11, 0);
let raw_counter = u32::from_be_bytes(buf[1..5].try_into().unwrap());
assert_eq!(raw_counter, 0x20102030);
assert_eq!(buf[5], 0);
}
#[test]
fn test_datetime_now() {
let now = Utc::now();
let cuc_now = TimeProviderCcsdsEpoch::from_now(FractionalResolution::SixtyNs);
assert!(cuc_now.is_ok());
let cuc_now = cuc_now.unwrap();
let dt_opt = cuc_now.date_time();
assert!(dt_opt.is_some());
let dt = dt_opt.unwrap();
let diff = dt - now;
assert!(diff.num_milliseconds() < 1000);
println!("datetime from cuc: {}", dt);
println!("datetime now: {}", now);
}
#[test]
fn test_read_no_fractions() {
let mut buf: [u8; 16] = [0; 16];
let zero_cuc =
TimeProviderCcsdsEpoch::new_generic(WidthCounterPair(4, 0x20102030), None).unwrap();
zero_cuc.write_to_bytes(&mut buf).unwrap();
let cuc_read_back =
TimeProviderCcsdsEpoch::from_bytes(&buf).expect("reading cuc timestamp failed");
assert_eq!(cuc_read_back, zero_cuc);
assert_eq!(cuc_read_back.width_counter_pair().1, 0x20102030);
assert_eq!(cuc_read_back.width_fractions_pair(), None);
}
#[test]
fn invalid_read_len() {
let mut buf: [u8; 16] = [0; 16];
for i in 0..2 {
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
{
assert_eq!(e.found, i);
assert_eq!(e.expected, 2);
}
}
let large_stamp = TimeProviderCcsdsEpoch::new_with_fine_fractions(22, 300).unwrap();
large_stamp.write_to_bytes(&mut buf).unwrap();
for i in 2..large_stamp.len_as_bytes() - 1 {
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
{
assert_eq!(e.found, i);
assert_eq!(e.expected, large_stamp.len_as_bytes());
}
}
}
#[test]
fn write_and_read_tiny_stamp() {
let mut buf = [0; 2];
let cuc = TimeProviderCcsdsEpoch::new_generic(WidthCounterPair(1, 200), None);
assert!(cuc.is_ok());
let cuc = cuc.unwrap();
assert_eq!(cuc.len_as_bytes(), 2);
let res = cuc.write_to_bytes(&mut buf);
assert!(res.is_ok());
let written = res.unwrap();
assert_eq!(written, 2);
assert_eq!(buf[1], 200);
let cuc_read_back = TimeProviderCcsdsEpoch::from_bytes(&buf);
assert!(cuc_read_back.is_ok());
let cuc_read_back = cuc_read_back.unwrap();
assert_eq!(cuc_read_back, cuc);
}
#[test]
fn write_slightly_larger_stamp() {
let mut buf = [0; 4];
let cuc = TimeProviderCcsdsEpoch::new_generic(WidthCounterPair(2, 40000), None);
assert!(cuc.is_ok());
let cuc = cuc.unwrap();
assert_eq!(cuc.len_as_bytes(), 3);
let res = cuc.write_to_bytes(&mut buf);
assert!(res.is_ok());
let written = res.unwrap();
assert_eq!(written, 3);
assert_eq!(u16::from_be_bytes(buf[1..3].try_into().unwrap()), 40000);
let cuc_read_back = TimeProviderCcsdsEpoch::from_bytes(&buf);
assert!(cuc_read_back.is_ok());
let cuc_read_back = cuc_read_back.unwrap();
assert_eq!(cuc_read_back, cuc);
}
#[test]
fn invalid_buf_len_for_read() {}
#[test]
fn write_read_three_byte_cntr_stamp() {
let mut buf = [0; 4];
let cuc = TimeProviderCcsdsEpoch::new_generic(WidthCounterPair(3, 2_u32.pow(24) - 2), None);
assert!(cuc.is_ok());
let cuc = cuc.unwrap();
assert_eq!(cuc.len_as_bytes(), 4);
let res = cuc.write_to_bytes(&mut buf);
assert!(res.is_ok());
let written = res.unwrap();
assert_eq!(written, 4);
let mut temp_buf = [0; 4];
temp_buf[1..4].copy_from_slice(&buf[1..4]);
assert_eq!(u32::from_be_bytes(temp_buf), 2_u32.pow(24) - 2);
let cuc_read_back = TimeProviderCcsdsEpoch::from_bytes(&buf);
assert!(cuc_read_back.is_ok());
let cuc_read_back = cuc_read_back.unwrap();
assert_eq!(cuc_read_back, cuc);
}
#[test]
fn test_write_invalid_buf() {
let mut buf: [u8; 16] = [0; 16];
let res = TimeProviderCcsdsEpoch::new_with_fine_fractions(0, 0);
let cuc = res.unwrap();
for i in 0..cuc.len_as_bytes() - 1 {
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
{
assert_eq!(e.expected, cuc.len_as_bytes());
assert_eq!(e.found, i);
} else {
panic!("unexpected error: {}", err);
}
}
}
#[test]
fn invalid_ccsds_stamp_type() {
let mut buf: [u8; 16] = [0; 16];
buf[0] |= (CcsdsTimeCodes::CucAgencyEpoch as u8) << 4;
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);
} else {
panic!("unexpected error: {}", err);
}
}
#[test]
fn test_write_with_coarse_fractions() {
let mut buf: [u8; 16] = [0; 16];
let cuc = TimeProviderCcsdsEpoch::new_with_coarse_fractions(0x30201060, 120);
assert!(cuc.fractions.is_some());
assert_eq!(cuc.fractions.unwrap().1, 120);
assert_eq!(cuc.fractions.unwrap().0, FractionalResolution::FourMs);
let res = cuc.write_to_bytes(&mut buf);
assert!(res.is_ok());
let written = res.unwrap();
assert_eq!(written, 6);
assert_eq!(buf[5], 120);
assert_eq!(buf[6], 0);
assert_eq!(
u32::from_be_bytes(buf[1..5].try_into().unwrap()),
0x30201060
);
}
#[test]
fn test_read_with_coarse_fractions() {
let mut buf: [u8; 16] = [0; 16];
let cuc = TimeProviderCcsdsEpoch::new_with_coarse_fractions(0x30201060, 120);
let res = cuc.write_to_bytes(&mut buf);
assert!(res.is_ok());
let res = TimeProviderCcsdsEpoch::from_bytes(&buf);
assert!(res.is_ok());
let read_back = res.unwrap();
assert_eq!(read_back, cuc);
}
#[test]
fn test_write_with_medium_fractions() {
let mut buf: [u8; 16] = [0; 16];
let cuc = TimeProviderCcsdsEpoch::new_with_medium_fractions(0x30303030, 30000);
let res = cuc.write_to_bytes(&mut buf);
assert!(res.is_ok());
let written = res.unwrap();
assert_eq!(written, 7);
assert_eq!(u16::from_be_bytes(buf[5..7].try_into().unwrap()), 30000);
assert_eq!(buf[7], 0);
}
#[test]
fn test_read_with_medium_fractions() {
let mut buf: [u8; 16] = [0; 16];
let cuc = TimeProviderCcsdsEpoch::new_with_medium_fractions(0x30303030, 30000);
let res = cuc.write_to_bytes(&mut buf);
assert!(res.is_ok());
let res = TimeProviderCcsdsEpoch::from_bytes(&buf);
assert!(res.is_ok());
let cuc_read_back = res.unwrap();
assert_eq!(cuc_read_back, cuc);
}
#[test]
fn test_write_with_fine_fractions() {
let mut buf: [u8; 16] = [0; 16];
let cuc =
TimeProviderCcsdsEpoch::new_with_fine_fractions(0x30303030, u16::MAX as u32 + 60000);
assert!(cuc.is_ok());
let cuc = cuc.unwrap();
let res = cuc.write_to_bytes(&mut buf);
let written = res.unwrap();
assert_eq!(written, 8);
let mut dummy_buf: [u8; 4] = [0; 4];
dummy_buf[1..4].copy_from_slice(&buf[5..8]);
assert_eq!(u32::from_be_bytes(dummy_buf), u16::MAX as u32 + 60000);
assert_eq!(buf[8], 0);
}
#[test]
fn test_read_with_fine_fractions() {
let mut buf: [u8; 16] = [0; 16];
let cuc =
TimeProviderCcsdsEpoch::new_with_fine_fractions(0x30303030, u16::MAX as u32 + 60000);
assert!(cuc.is_ok());
let cuc = cuc.unwrap();
let res = cuc.write_to_bytes(&mut buf);
assert!(res.is_ok());
let res = TimeProviderCcsdsEpoch::from_bytes(&buf);
assert!(res.is_ok());
let cuc_read_back = res.unwrap();
assert_eq!(cuc_read_back, cuc);
}
#[test]
fn test_fractional_converter() {
let ns = convert_fractional_part_to_ns(FractionalPart(FractionalResolution::FourMs, 2));
// The formula for this is 2/255 * 10e9 = 7.843.137.
assert_eq!(ns, 7843137);
// This is the largest value we should be able to pass without this function panicking.
let ns = convert_fractional_part_to_ns(FractionalPart(
FractionalResolution::SixtyNs,
2_u32.pow(24) - 2,
));
assert_eq!(ns, 999999940);
}
#[test]
#[should_panic]
fn test_fractional_converter_invalid_input() {
convert_fractional_part_to_ns(FractionalPart(FractionalResolution::FourMs, 256));
}
#[test]
#[should_panic]
fn test_fractional_converter_invalid_input_2() {
convert_fractional_part_to_ns(FractionalPart(
FractionalResolution::SixtyNs,
2_u32.pow(32) - 1,
));
}
#[test]
fn fractional_part_formula() {
let fractional_part =
fractional_part_from_subsec_ns(FractionalResolution::FourMs, 7843138).unwrap();
assert_eq!(fractional_part.1, 2);
}
#[test]
fn fractional_part_formula_2() {
let fractional_part =
fractional_part_from_subsec_ns(FractionalResolution::FourMs, 12000000).unwrap();
assert_eq!(fractional_part.1, 3);
}
#[test]
fn fractional_part_formula_3() {
let one_fraction_with_width_two_in_ns =
10_u64.pow(9) as f64 / (2_u32.pow(8 * 2) - 1) as f64;
assert_eq!(one_fraction_with_width_two_in_ns.ceil(), 15260.0);
let hundred_fractions_and_some =
(100.0 * one_fraction_with_width_two_in_ns).floor() as u64 + 7000;
let fractional_part = fractional_part_from_subsec_ns(
FractionalResolution::FifteenUs,
hundred_fractions_and_some,
)
.unwrap();
assert_eq!(fractional_part.1, 100);
// Using exactly 101.0 can yield values which will later be rounded down to 100
let hundred_and_one_fractions =
(101.001 * one_fraction_with_width_two_in_ns).floor() as u64;
let fractional_part = fractional_part_from_subsec_ns(
FractionalResolution::FifteenUs,
hundred_and_one_fractions,
)
.unwrap();
assert_eq!(fractional_part.1, 101);
}
#[test]
fn update_fractions() {
let mut stamp = TimeProviderCcsdsEpoch::new(2000);
let res = stamp.set_fractions(FractionalPart(FractionalResolution::SixtyNs, 5000));
assert!(res.is_ok());
assert!(stamp.fractions.is_some());
let fractions = stamp.fractions.unwrap();
assert_eq!(fractions.0, FractionalResolution::SixtyNs);
assert_eq!(fractions.1, 5000);
}
#[test]
fn set_fract_resolution() {
let mut stamp = TimeProviderCcsdsEpoch::new(2000);
stamp.set_fractional_resolution(FractionalResolution::SixtyNs);
assert!(stamp.fractions.is_some());
let fractions = stamp.fractions.unwrap();
assert_eq!(fractions.0, FractionalResolution::SixtyNs);
assert_eq!(fractions.1, 0);
let res = stamp.update_from_now();
assert!(res.is_ok());
}
#[test]
fn assert_largest_fractions() {
let fractions =
fractional_part_from_subsec_ns(FractionalResolution::SixtyNs, 10u64.pow(9) - 1)
.unwrap();
// The value can not be larger than representable by 3 bytes
// Assert that the maximum resolution can be reached
assert_eq!(fractions.1, 2_u32.pow(3 * 8) - 2);
}
}

View File

@ -7,7 +7,6 @@ use core::fmt::{Display, Formatter};
#[cfg(not(feature = "std"))]
use num_traits::float::FloatCore;
use crate::time::cuc::CucError;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "std")]
@ -73,7 +72,7 @@ impl From<cds::CdsError> for TimestampError {
}
impl From<cuc::CucError> for TimestampError {
fn from(e: CucError) -> Self {
fn from(e: cuc::CucError) -> Self {
TimestampError::CucError(e)
}
}
@ -163,6 +162,16 @@ pub const fn ccsds_to_unix_days(ccsds_days: i64) -> i64 {
ccsds_days + DAYS_CCSDS_TO_UNIX as i64
}
/// Similar to [unix_to_ccsds_days] but converts the epoch instead, which is the number of elpased
/// seconds since the CCSDS and UNIX epoch times.
pub const fn unix_epoch_to_ccsds_epoch(unix_epoch: u64) -> u64 {
(unix_epoch as i64 - (DAYS_CCSDS_TO_UNIX as i64 * SECONDS_PER_DAY as i64)) as u64
}
pub const fn ccsds_epoch_to_unix_epoch(ccsds_epoch: u64) -> u64 {
(ccsds_epoch as i64 + (DAYS_CCSDS_TO_UNIX as i64 * SECONDS_PER_DAY as i64)) as u64
}
#[cfg(feature = "std")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
pub fn ms_of_day_using_sysclock() -> u32 {
@ -218,4 +227,17 @@ mod tests {
let sec_floats = seconds_since_epoch();
assert!(sec_floats > 0.0);
}
#[test]
fn test_ccsds_epoch() {
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
let unix_epoch = now.as_secs();
let ccsds_epoch = unix_epoch_to_ccsds_epoch(now.as_secs());
assert!(ccsds_epoch > unix_epoch);
assert_eq!((ccsds_epoch - unix_epoch) % SECONDS_PER_DAY as u64, 0);
let days_diff = (ccsds_epoch - unix_epoch) / SECONDS_PER_DAY as u64;
assert_eq!(days_diff, -DAYS_CCSDS_TO_UNIX as u64);
}
}

View File

@ -108,18 +108,18 @@ pub mod zc {
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PusTmSecondaryHeader<'slice> {
pub struct PusTmSecondaryHeader<'stamp> {
pus_version: PusVersion,
pub sc_time_ref_status: u8,
pub service: u8,
pub subservice: u8,
pub msg_counter: u16,
pub dest_id: u16,
pub time_stamp: &'slice [u8],
pub time_stamp: &'stamp [u8],
}
impl<'slice> PusTmSecondaryHeader<'slice> {
pub fn new_simple(service: u8, subservice: u8, time_stamp: &'slice [u8]) -> Self {
impl<'stamp> PusTmSecondaryHeader<'stamp> {
pub fn new_simple(service: u8, subservice: u8, time_stamp: &'stamp [u8]) -> Self {
PusTmSecondaryHeader {
pus_version: PusVersion::PusC,
sc_time_ref_status: 0,
@ -136,7 +136,7 @@ impl<'slice> PusTmSecondaryHeader<'slice> {
subservice: u8,
msg_counter: u16,
dest_id: u16,
time_stamp: &'slice [u8],
time_stamp: &'stamp [u8],
) -> Self {
PusTmSecondaryHeader {
pus_version: PusVersion::PusC,
@ -201,21 +201,26 @@ impl<'slice> TryFrom<zc::PusTmSecHeader<'slice>> for PusTmSecondaryHeader<'slice
/// provider like [postcard](https://docs.rs/postcard/latest/postcard/).
///
/// There is no spare bytes support yet.
///
/// # Lifetimes
///
/// * `'src_data` - Life time of a buffer where the user provided time stamp and source data will
/// be serialized into.
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PusTm<'slice> {
pub struct PusTm<'src_data> {
pub sp_header: SpHeader,
pub sec_header: PusTmSecondaryHeader<'slice>,
pub sec_header: PusTmSecondaryHeader<'src_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<&'slice [u8]>,
source_data: Option<&'slice [u8]>,
raw_data: Option<&'src_data [u8]>,
source_data: Option<&'src_data [u8]>,
crc16: Option<u16>,
}
impl<'slice> PusTm<'slice> {
impl<'src_data> PusTm<'src_data> {
/// Generates a new struct instance.
///
/// # Arguments
@ -230,8 +235,8 @@ impl<'slice> PusTm<'slice> {
/// the correct value to this field manually
pub fn new(
sp_header: &mut SpHeader,
sec_header: PusTmSecondaryHeader<'slice>,
source_data: Option<&'slice [u8]>,
sec_header: PusTmSecondaryHeader<'src_data>,
source_data: Option<&'src_data [u8]>,
set_ccsds_len: bool,
) -> Self {
sp_header.set_packet_type(PacketType::Tm);
@ -259,11 +264,11 @@ impl<'slice> PusTm<'slice> {
length
}
pub fn time_stamp(&self) -> &'slice [u8] {
pub fn time_stamp(&self) -> &'src_data [u8] {
self.sec_header.time_stamp
}
pub fn source_data(&self) -> Option<&'slice [u8]> {
pub fn source_data(&self) -> Option<&'src_data [u8]> {
self.source_data
}
@ -390,7 +395,7 @@ impl<'slice> PusTm<'slice> {
/// the instance and the found byte length of the packet. The timestamp length needs to be
/// known beforehand.
pub fn from_bytes(
slice: &'slice [u8],
slice: &'src_data [u8],
timestamp_len: usize,
) -> Result<(Self, usize), PusError> {
let raw_data_len = slice.len();