12 Commits

Author SHA1 Message Date
85bfcad111 bump changelog
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2022-12-01 01:22:19 +01:00
03d112cbef update spacepackets deps
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2022-11-30 01:05:37 +01:00
1ec21c1bff use const instead of struct field
All checks were successful
Rust/spacepackets/pipeline/head This commit looks good
2022-11-20 18:42:35 +01:00
c750f94fba use non-deprecated API
Some checks failed
Rust/spacepackets/pipeline/head There was a failure building this commit
2022-11-19 02:39:25 +01:00
1d6cf3a75d update changelog
Some checks failed
Rust/spacepackets/pipeline/head There was a failure building this commit
2022-11-02 11:10:41 +01:00
f8199ca87a better docs 2022-11-02 00:38:59 +01:00
4c1101f65f better naming 2022-11-02 00:36:18 +01:00
38b789ca6d cargo fmt 2022-10-31 00:23:13 +01:00
d391891991 add EcssEnumerationExt trait extension 2022-10-31 00:22:28 +01:00
65e85f20e0 doc cfg support
Some checks failed
Rust/spacepackets/pipeline/head There was a failure building this commit
2022-10-26 00:22:56 +02:00
a2673c9870 make ToBeBytes trait public
Some checks failed
Rust/spacepackets/pipeline/head There was a failure building this commit
2022-10-23 18:35:56 +02:00
603f688ac3 small clippy fix
Some checks failed
Rust/spacepackets/pipeline/head There was a failure building this commit
2022-10-15 19:56:17 +02:00
7 changed files with 62 additions and 27 deletions

View File

@ -8,6 +8,18 @@ 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 # [v0.2.0] 13.09.2022
## Added ## Added

View File

@ -1,6 +1,6 @@
[package] [package]
name = "spacepackets" name = "spacepackets"
version = "0.2.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"]

View File

@ -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};
@ -158,7 +159,7 @@ 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 length /// 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 /// 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 /// value and only requires implementors to implement a function which writes the enumeration into
/// a raw byte format. /// a raw byte format.
@ -168,10 +169,12 @@ pub trait EcssEnumeration {
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;
} }
@ -208,6 +211,7 @@ impl ToBeBytes for u64 {
} }
} }
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct GenericEcssEnumWrapper<TYPE> { pub struct GenericEcssEnumWrapper<TYPE> {
val: TYPE, val: TYPE,
} }
@ -227,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(),
@ -239,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>;
@ -254,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);
} }
@ -264,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);
@ -274,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 {
@ -293,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);
@ -305,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 {

View File

@ -65,11 +65,12 @@ 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,
@ -136,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
@ -182,7 +183,7 @@ impl PacketSequenceCtrl {
seq_flags, seq_flags,
seq_count: 0, seq_count: 0,
}; };
psc.set_seq_count(seq_count).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

View File

@ -370,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;

View File

@ -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)
@ -111,7 +114,6 @@ pub trait CcsdsTimeProvider {
/// ``` /// ```
#[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,
@ -121,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: (Cds as u8) << 4,
ccsds_days, ccsds_days,
ms_of_day, ms_of_day,
unix_seconds: 0, unix_seconds: 0,
@ -133,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();
@ -140,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,
@ -151,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();
@ -168,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())
} }
@ -193,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;
}
} }
} }
@ -203,7 +210,7 @@ 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 {
@ -229,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(())

View File

@ -352,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 =