spacepackets/src/ecss/tm.rs

1238 lines
43 KiB
Rust
Raw Normal View History

2022-07-31 13:31:14 +02:00
//! This module contains all components required to create a ECSS PUS C telemetry packets according
//! to [ECSS-E-ST-70-41C](https://ecss.nl/standard/ecss-e-st-70-41c-space-engineering-telemetry-and-telecommand-packet-utilization-15-april-2016/).
use crate::ecss::{
2023-07-10 01:11:42 +02:00
calc_pus_crc16, ccsds_impl, crc_from_raw_data, sp_header_impls, user_data_from_raw,
verify_crc16_ccitt_false_from_raw_to_pus_error, CrcType, PusError, PusPacket, PusVersion,
2023-11-24 16:15:46 +01:00
WritablePusPacket,
2022-07-31 14:24:16 +02:00
};
use crate::{
2023-08-18 10:09:32 +02:00
ByteConversionError, CcsdsPacket, PacketType, SequenceFlags, SpHeader, CCSDS_HEADER_LEN,
CRC_CCITT_FALSE, MAX_APID, MAX_SEQ_COUNT,
2022-07-31 13:31:14 +02:00
};
2022-07-31 02:27:27 +02:00
use core::mem::size_of;
2022-12-04 12:17:36 +01:00
#[cfg(feature = "serde")]
2022-07-31 02:27:27 +02:00
use serde::{Deserialize, Serialize};
use zerocopy::AsBytes;
2022-06-18 22:48:51 +02:00
2022-07-31 11:38:58 +02:00
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
2022-07-31 13:31:14 +02:00
use delegate::delegate;
2022-07-31 11:38:58 +02:00
2023-07-11 22:12:17 +02:00
use crate::time::{TimeWriter, TimestampError};
2023-07-10 01:11:42 +02:00
2024-02-07 11:07:20 +01:00
use self::zc::PusTmSecHeaderWithoutTimestamp;
pub trait IsPusTelemetry {}
2022-07-31 02:27:27 +02:00
/// Length without timestamp
2024-02-07 11:07:20 +01:00
pub const PUS_TM_MIN_SEC_HEADER_LEN: usize = 7;
2022-07-31 02:27:27 +02:00
pub const PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA: usize =
2024-02-07 11:07:20 +01:00
CCSDS_HEADER_LEN + PUS_TM_MIN_SEC_HEADER_LEN + size_of::<CrcType>();
2022-07-31 02:27:27 +02:00
2022-12-04 17:11:44 +01:00
pub trait GenericPusTmSecondaryHeader {
2022-07-31 13:31:14 +02:00
fn pus_version(&self) -> PusVersion;
fn sc_time_ref_status(&self) -> u8;
fn service(&self) -> u8;
fn subservice(&self) -> u8;
fn msg_counter(&self) -> u16;
fn dest_id(&self) -> u16;
}
2022-07-31 02:27:27 +02:00
pub mod zc {
2022-12-04 17:11:44 +01:00
use super::GenericPusTmSecondaryHeader;
2022-07-31 02:27:27 +02:00
use crate::ecss::{PusError, PusVersion};
2023-08-28 18:45:24 +02:00
use zerocopy::{AsBytes, FromBytes, FromZeroes, NetworkEndian, Unaligned, U16};
2022-07-31 02:27:27 +02:00
2023-08-28 18:45:24 +02:00
#[derive(FromBytes, FromZeroes, AsBytes, Unaligned)]
2022-07-31 02:27:27 +02:00
#[repr(C)]
pub struct PusTmSecHeaderWithoutTimestamp {
pus_version_and_sc_time_ref_status: u8,
service: u8,
subservice: u8,
msg_counter: U16<NetworkEndian>,
dest_id: U16<NetworkEndian>,
}
2022-07-31 13:31:14 +02:00
pub struct PusTmSecHeader<'slice> {
pub(crate) zc_header: PusTmSecHeaderWithoutTimestamp,
2023-07-11 14:16:17 +02:00
pub(crate) timestamp: &'slice [u8],
2022-07-31 13:31:14 +02:00
}
2023-07-09 12:27:44 +02:00
impl TryFrom<crate::ecss::tm::PusTmSecondaryHeader<'_>> for PusTmSecHeaderWithoutTimestamp {
2022-07-31 02:27:27 +02:00
type Error = PusError;
2023-07-09 12:27:44 +02:00
fn try_from(header: crate::ecss::tm::PusTmSecondaryHeader) -> Result<Self, Self::Error> {
2022-07-31 02:27:27 +02:00
if header.pus_version != PusVersion::PusC {
return Err(PusError::VersionNotSupported(header.pus_version));
}
Ok(PusTmSecHeaderWithoutTimestamp {
pus_version_and_sc_time_ref_status: ((header.pus_version as u8) << 4)
| header.sc_time_ref_status,
service: header.service,
subservice: header.subservice,
msg_counter: U16::from(header.msg_counter),
dest_id: U16::from(header.dest_id),
})
}
}
impl PusTmSecHeaderWithoutTimestamp {
2022-09-11 20:50:46 +02:00
pub fn write_to_bytes(&self, slice: &mut [u8]) -> Option<()> {
2022-07-31 02:27:27 +02:00
self.write_to(slice)
}
pub fn from_bytes(slice: &[u8]) -> Option<Self> {
Self::read_from(slice)
}
}
2022-07-31 13:31:14 +02:00
2022-12-04 17:11:44 +01:00
impl GenericPusTmSecondaryHeader for PusTmSecHeaderWithoutTimestamp {
2022-07-31 13:31:14 +02:00
fn pus_version(&self) -> PusVersion {
PusVersion::try_from(self.pus_version_and_sc_time_ref_status >> 4 & 0b1111)
.unwrap_or(PusVersion::Invalid)
}
fn sc_time_ref_status(&self) -> u8 {
self.pus_version_and_sc_time_ref_status & 0b1111
}
fn service(&self) -> u8 {
self.service
}
fn subservice(&self) -> u8 {
self.subservice
}
fn msg_counter(&self) -> u16 {
self.msg_counter.get()
}
fn dest_id(&self) -> u16 {
self.dest_id.get()
}
}
2022-07-31 02:27:27 +02:00
}
2022-12-04 12:17:36 +01:00
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2024-03-29 13:42:02 +01:00
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2023-01-10 16:19:21 +01:00
pub struct PusTmSecondaryHeader<'stamp> {
2022-07-31 02:27:27 +02:00
pus_version: PusVersion,
pub sc_time_ref_status: u8,
pub service: u8,
pub subservice: u8,
pub msg_counter: u16,
pub dest_id: u16,
2024-04-03 13:30:01 +02:00
pub time_stamp: &'stamp [u8],
2022-07-31 02:27:27 +02:00
}
2023-01-10 16:19:21 +01:00
impl<'stamp> PusTmSecondaryHeader<'stamp> {
2024-04-03 13:30:01 +02:00
pub fn new_simple(service: u8, subservice: u8, time_stamp: &'stamp [u8]) -> Self {
Self::new(service, subservice, 0, 0, time_stamp)
2023-01-16 11:56:25 +01:00
}
2023-01-20 19:46:26 +01:00
/// Like [Self::new_simple] but without a timestamp.
2023-01-16 11:56:25 +01:00
pub fn new_simple_no_timestamp(service: u8, subservice: u8) -> Self {
2024-04-03 13:30:01 +02:00
Self::new(service, subservice, 0, 0, &[])
2022-07-31 02:27:27 +02:00
}
pub fn new(
service: u8,
subservice: u8,
msg_counter: u16,
dest_id: u16,
2024-04-03 13:30:01 +02:00
time_stamp: &'stamp [u8],
2022-07-31 02:27:27 +02:00
) -> Self {
PusTmSecondaryHeader {
pus_version: PusVersion::PusC,
sc_time_ref_status: 0,
service,
subservice,
msg_counter,
dest_id,
2024-04-03 13:30:01 +02:00
time_stamp,
2022-07-31 02:27:27 +02:00
}
}
}
2022-12-04 17:11:44 +01:00
impl GenericPusTmSecondaryHeader for PusTmSecondaryHeader<'_> {
2022-07-31 13:31:14 +02:00
fn pus_version(&self) -> PusVersion {
self.pus_version
}
fn sc_time_ref_status(&self) -> u8 {
self.sc_time_ref_status
}
fn service(&self) -> u8 {
self.service
}
fn subservice(&self) -> u8 {
self.subservice
}
fn msg_counter(&self) -> u16 {
self.msg_counter
}
fn dest_id(&self) -> u16 {
self.dest_id
}
}
impl<'slice> TryFrom<zc::PusTmSecHeader<'slice>> for PusTmSecondaryHeader<'slice> {
type Error = ();
fn try_from(sec_header: zc::PusTmSecHeader<'slice>) -> Result<Self, Self::Error> {
Ok(PusTmSecondaryHeader {
pus_version: sec_header.zc_header.pus_version(),
sc_time_ref_status: sec_header.zc_header.sc_time_ref_status(),
service: sec_header.zc_header.service(),
subservice: sec_header.zc_header.subservice(),
msg_counter: sec_header.zc_header.msg_counter(),
dest_id: sec_header.zc_header.dest_id(),
2024-04-03 13:30:01 +02:00
time_stamp: sec_header.timestamp,
2022-07-31 13:31:14 +02:00
})
}
}
2023-01-22 18:26:38 +01:00
/// This class models the PUS C telemetry packet. It is the primary data structure to generate the
2023-07-10 01:11:42 +02:00
/// raw byte representation of PUS telemetry.
2022-07-31 02:27:27 +02:00
///
2022-12-05 09:03:40 +01:00
/// This class also derives the [serde::Serialize] and [serde::Deserialize] trait if the [serde]
/// feature is used which allows to send around TM packets in a raw byte format using a serde
/// provider like [postcard](https://docs.rs/postcard/latest/postcard/).
2022-07-31 13:31:14 +02:00
///
2022-07-31 02:27:27 +02:00
/// There is no spare bytes support yet.
2023-01-10 16:20:50 +01:00
///
/// # Lifetimes
///
2023-07-10 01:11:42 +02:00
/// * `'raw_data` - This is the lifetime of the user provided time stamp and source data.
2023-01-26 19:24:41 +01:00
#[derive(Eq, Debug, Copy, Clone)]
2022-12-04 12:17:36 +01:00
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2024-03-29 13:42:02 +01:00
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2024-03-29 14:06:52 +01:00
pub struct PusTmCreator<'time, 'raw_data> {
2022-07-31 02:27:27 +02:00
pub sp_header: SpHeader,
2024-03-29 14:13:44 +01:00
#[cfg_attr(feature = "serde", serde(borrow))]
2024-03-29 14:06:52 +01:00
pub sec_header: PusTmSecondaryHeader<'time>,
2023-07-11 00:03:07 +02:00
source_data: &'raw_data [u8],
2024-03-29 14:06:52 +01:00
/// If this is set to false, a manual call to [Self::calc_own_crc16] or
/// [Self::update_packet_fields] is necessary for the serialized or cached CRC16 to be valid.
2022-07-31 02:27:27 +02:00
pub calc_crc_on_serialization: bool,
}
2024-03-29 14:06:52 +01:00
impl<'time, 'raw_data> PusTmCreator<'time, 'raw_data> {
2022-07-31 02:27:27 +02:00
/// Generates a new struct instance.
///
/// # Arguments
///
/// * `sp_header` - Space packet header information. The correct packet type will be set
/// automatically
2022-07-31 13:31:14 +02:00
/// * `sec_header` - Information contained in the secondary header, including the service
2022-07-31 02:27:27 +02:00
/// and subservice type
2023-12-03 19:45:31 +01:00
/// * `source_data` - Custom application data
2022-07-31 02:27:27 +02:00
/// * `set_ccsds_len` - Can be used to automatically update the CCSDS space packet data length
2024-03-29 14:06:52 +01:00
/// field. If this is not set to true, [Self::update_ccsds_data_len] can be called to set
2022-07-31 02:27:27 +02:00
/// the correct value to this field manually
pub fn new(
sp_header: &mut SpHeader,
2024-03-29 14:06:52 +01:00
sec_header: PusTmSecondaryHeader<'time>,
2023-12-03 19:45:31 +01:00
source_data: &'raw_data [u8],
2022-07-31 02:27:27 +02:00
set_ccsds_len: bool,
) -> Self {
2022-07-31 11:38:58 +02:00
sp_header.set_packet_type(PacketType::Tm);
sp_header.set_sec_header_flag();
2023-07-10 01:11:42 +02:00
let mut pus_tm = Self {
2022-07-31 02:27:27 +02:00
sp_header: *sp_header,
2023-12-03 19:45:31 +01:00
source_data,
2022-07-31 02:27:27 +02:00
sec_header,
calc_crc_on_serialization: true,
};
if set_ccsds_len {
pus_tm.update_ccsds_data_len();
}
pus_tm
}
2023-07-11 14:16:17 +02:00
pub fn new_simple(
sp_header: &mut SpHeader,
service: u8,
subservice: u8,
2023-07-11 22:12:17 +02:00
time_provider: &impl TimeWriter,
2024-03-29 14:06:52 +01:00
stamp_buf: &'time mut [u8],
2023-12-07 13:49:59 +01:00
source_data: Option<&'raw_data [u8]>,
2023-07-11 14:16:17 +02:00
set_ccsds_len: bool,
) -> Result<Self, TimestampError> {
2023-07-11 22:12:17 +02:00
let stamp_size = time_provider.write_to_bytes(stamp_buf)?;
let sec_header =
PusTmSecondaryHeader::new_simple(service, subservice, &stamp_buf[0..stamp_size]);
2023-12-07 13:49:59 +01:00
Ok(Self::new(
sp_header,
sec_header,
source_data.unwrap_or(&[]),
set_ccsds_len,
))
2023-07-11 14:16:17 +02:00
}
2023-12-03 19:45:31 +01:00
pub fn new_no_source_data(
sp_header: &mut SpHeader,
2024-03-29 14:06:52 +01:00
sec_header: PusTmSecondaryHeader<'time>,
2023-12-03 19:45:31 +01:00
set_ccsds_len: bool,
) -> Self {
2023-12-07 13:49:59 +01:00
Self::new(sp_header, sec_header, &[], set_ccsds_len)
2023-12-03 19:45:31 +01:00
}
2023-12-07 13:49:59 +01:00
2023-07-11 22:12:17 +02:00
pub fn timestamp(&self) -> &[u8] {
2024-04-03 13:30:01 +02:00
self.sec_header.time_stamp
2022-07-31 13:43:40 +02:00
}
2023-07-11 00:03:07 +02:00
pub fn source_data(&self) -> &[u8] {
self.source_data
}
2022-07-31 14:24:16 +02:00
pub fn set_dest_id(&mut self, dest_id: u16) {
self.sec_header.dest_id = dest_id;
}
pub fn set_msg_counter(&mut self, msg_counter: u16) {
self.sec_header.msg_counter = msg_counter
}
pub fn set_sc_time_ref_status(&mut self, sc_time_ref_status: u8) {
self.sec_header.sc_time_ref_status = sc_time_ref_status & 0b1111;
}
sp_header_impls!();
2024-03-29 14:06:52 +01:00
/// This is called automatically if the `set_ccsds_len` argument in the [Self::new] call was
2022-07-31 13:31:14 +02:00
/// used.
2022-07-31 02:27:27 +02:00
/// If this was not done or the time stamp or source data is set or changed after construction,
/// this function needs to be called to ensure that the data length field of the CCSDS header
/// is set correctly
pub fn update_ccsds_data_len(&mut self) {
self.sp_header.data_len =
2023-11-24 16:15:46 +01:00
self.len_written() as u16 - size_of::<crate::zc::SpHeader>() as u16 - 1;
2022-07-31 02:27:27 +02:00
}
/// This function should be called before the TM packet is serialized if
2024-03-29 14:06:52 +01:00
/// [Self::calc_crc_on_serialization] is set to False. It will calculate and cache the CRC16.
2023-07-10 01:11:42 +02:00
pub fn calc_own_crc16(&self) -> u16 {
2022-07-31 02:27:27 +02:00
let mut digest = CRC_CCITT_FALSE.digest();
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
digest.update(sph_zc.as_bytes());
let pus_tc_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
digest.update(pus_tc_header.as_bytes());
2024-04-03 13:30:01 +02:00
digest.update(self.sec_header.time_stamp);
2023-07-11 00:03:07 +02:00
digest.update(self.source_data);
2023-07-10 01:11:42 +02:00
digest.finalize()
2022-07-31 02:27:27 +02:00
}
2024-03-29 14:06:52 +01:00
/// This helper function calls both [Self::update_ccsds_data_len] and [Self::calc_own_crc16]
2022-07-31 02:27:27 +02:00
pub fn update_packet_fields(&mut self) {
self.update_ccsds_data_len();
}
2024-03-25 13:42:18 +01:00
/// Write the raw PUS byte representation to a provided buffer.
pub fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, ByteConversionError> {
let mut curr_idx = 0;
let total_size = self.len_written();
if total_size > slice.len() {
return Err(ByteConversionError::ToSliceTooSmall {
found: slice.len(),
expected: total_size,
});
}
self.sp_header
.write_to_be_bytes(&mut slice[0..CCSDS_HEADER_LEN])?;
curr_idx += CCSDS_HEADER_LEN;
let sec_header_len = size_of::<zc::PusTmSecHeaderWithoutTimestamp>();
let sec_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
sec_header
.write_to_bytes(&mut slice[curr_idx..curr_idx + sec_header_len])
.ok_or(ByteConversionError::ZeroCopyToError)?;
curr_idx += sec_header_len;
2024-04-03 13:30:01 +02:00
slice[curr_idx..curr_idx + self.sec_header.time_stamp.len()]
.copy_from_slice(self.sec_header.time_stamp);
curr_idx += self.sec_header.time_stamp.len();
2024-03-25 13:42:18 +01:00
slice[curr_idx..curr_idx + self.source_data.len()].copy_from_slice(self.source_data);
curr_idx += self.source_data.len();
let mut digest = CRC_CCITT_FALSE.digest();
digest.update(&slice[0..curr_idx]);
slice[curr_idx..curr_idx + 2].copy_from_slice(&digest.finalize().to_be_bytes());
curr_idx += 2;
Ok(curr_idx)
}
2022-07-31 13:31:14 +02:00
/// Append the raw PUS byte representation to a provided [alloc::vec::Vec]
2022-07-31 11:38:58 +02:00
#[cfg(feature = "alloc")]
pub fn append_to_vec(&self, vec: &mut Vec<u8>) -> Result<usize, PusError> {
let sph_zc = crate::zc::SpHeader::from(self.sp_header);
2024-04-03 13:30:01 +02:00
let mut appended_len =
PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA + self.sec_header.time_stamp.len();
2023-07-11 00:03:07 +02:00
appended_len += self.source_data.len();
2022-07-31 11:38:58 +02:00
let start_idx = vec.len();
vec.extend_from_slice(sph_zc.as_bytes());
// The PUS version is hardcoded to PUS C
let sec_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
vec.extend_from_slice(sec_header.as_bytes());
2024-04-03 13:30:01 +02:00
vec.extend_from_slice(self.sec_header.time_stamp);
2023-07-11 00:03:07 +02:00
vec.extend_from_slice(self.source_data);
2023-07-10 01:11:42 +02:00
let mut digest = CRC_CCITT_FALSE.digest();
digest.update(&vec[start_idx..start_idx + appended_len - 2]);
vec.extend_from_slice(&digest.finalize().to_be_bytes());
2022-07-31 11:38:58 +02:00
Ok(appended_len)
}
2023-07-10 01:11:42 +02:00
}
2024-03-29 14:06:52 +01:00
impl WritablePusPacket for PusTmCreator<'_, '_> {
2023-11-24 16:15:46 +01:00
fn len_written(&self) -> usize {
2023-07-11 22:12:17 +02:00
PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA
2024-04-03 13:30:01 +02:00
+ self.sec_header.time_stamp.len()
2023-07-11 22:12:17 +02:00
+ self.source_data.len()
2023-07-10 01:11:42 +02:00
}
/// Write the raw PUS byte representation to a provided buffer.
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
2024-03-25 13:42:18 +01:00
Ok(Self::write_to_bytes(self, slice)?)
2023-07-10 01:11:42 +02:00
}
}
2024-03-29 14:06:52 +01:00
impl PartialEq for PusTmCreator<'_, '_> {
2023-07-10 01:11:42 +02:00
fn eq(&self, other: &Self) -> bool {
self.sp_header == other.sp_header
&& self.sec_header == other.sec_header
&& self.source_data == other.source_data
}
}
2024-03-29 14:06:52 +01:00
impl CcsdsPacket for PusTmCreator<'_, '_> {
2023-07-10 01:11:42 +02:00
ccsds_impl!();
}
2024-03-29 14:06:52 +01:00
impl PusPacket for PusTmCreator<'_, '_> {
2023-07-10 01:11:42 +02:00
delegate!(to self.sec_header {
fn pus_version(&self) -> PusVersion;
fn service(&self) -> u8;
fn subservice(&self) -> u8;
});
2022-07-31 13:31:14 +02:00
2023-07-11 00:03:07 +02:00
fn user_data(&self) -> &[u8] {
2023-07-10 01:11:42 +02:00
self.source_data
}
fn crc16(&self) -> Option<u16> {
Some(self.calc_own_crc16())
}
}
2024-03-29 14:06:52 +01:00
impl GenericPusTmSecondaryHeader for PusTmCreator<'_, '_> {
2023-07-10 01:11:42 +02:00
delegate!(to self.sec_header {
fn pus_version(&self) -> PusVersion;
fn service(&self) -> u8;
fn subservice(&self) -> u8;
fn dest_id(&self) -> u16;
fn msg_counter(&self) -> u16;
fn sc_time_ref_status(&self) -> u8;
});
}
2024-03-29 14:06:52 +01:00
impl IsPusTelemetry for PusTmCreator<'_, '_> {}
2023-07-10 01:11:42 +02:00
/// This class models the PUS C telemetry packet. It is the primary data structure to read
/// a telemetry packet from raw bytes.
///
/// This class also derives the [serde::Serialize] and [serde::Deserialize] trait if the [serde]
/// feature is used which allows to send around TM packets in a raw byte format using a serde
/// provider like [postcard](https://docs.rs/postcard/latest/postcard/).
///
/// There is no spare bytes support yet.
///
/// # Lifetimes
///
/// * `'raw_data` - Lifetime of the raw slice this class is constructed from.
#[derive(Eq, Debug, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2024-03-29 13:42:02 +01:00
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2023-07-10 01:11:42 +02:00
pub struct PusTmReader<'raw_data> {
pub sp_header: SpHeader,
pub sec_header: PusTmSecondaryHeader<'raw_data>,
#[cfg_attr(feature = "serde", serde(skip))]
raw_data: &'raw_data [u8],
2023-07-11 00:03:07 +02:00
source_data: &'raw_data [u8],
2023-07-10 01:11:42 +02:00
crc16: u16,
}
impl<'raw_data> PusTmReader<'raw_data> {
/// Create a [PusTmReader] instance from a raw slice. On success, it returns a tuple containing
2022-07-31 13:31:14 +02:00
/// the instance and the found byte length of the packet. The timestamp length needs to be
/// known beforehand.
2024-03-25 13:42:18 +01:00
///
/// This function will check the CRC-16 of the PUS packet and will return an appropriate
/// [PusError] if the check fails.
2023-07-10 01:11:42 +02:00
pub fn new(slice: &'raw_data [u8], timestamp_len: usize) -> Result<(Self, usize), PusError> {
2022-07-31 13:31:14 +02:00
let raw_data_len = slice.len();
if raw_data_len < PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA {
2023-12-03 15:45:11 +01:00
return Err(ByteConversionError::FromSliceTooSmall {
found: raw_data_len,
expected: PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA,
}
.into());
2022-07-31 13:31:14 +02:00
}
let mut current_idx = 0;
2022-12-05 01:41:35 +01:00
let (sp_header, _) = SpHeader::from_be_bytes(&slice[0..CCSDS_HEADER_LEN])?;
2022-07-31 13:31:14 +02:00
current_idx += 6;
2022-12-05 01:41:35 +01:00
let total_len = sp_header.total_len();
2023-12-03 15:45:11 +01:00
if raw_data_len < total_len {
return Err(ByteConversionError::FromSliceTooSmall {
found: raw_data_len,
expected: total_len,
}
.into());
}
if total_len < PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA {
return Err(ByteConversionError::FromSliceTooSmall {
found: total_len,
expected: PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA,
}
.into());
2022-07-31 13:31:14 +02:00
}
let sec_header_zc = zc::PusTmSecHeaderWithoutTimestamp::from_bytes(
2024-02-07 11:07:20 +01:00
&slice[current_idx..current_idx + PUS_TM_MIN_SEC_HEADER_LEN],
2022-07-31 13:31:14 +02:00
)
2022-09-13 09:52:59 +02:00
.ok_or(ByteConversionError::ZeroCopyFromError)?;
2024-02-07 11:07:20 +01:00
current_idx += PUS_TM_MIN_SEC_HEADER_LEN;
2022-07-31 13:31:14 +02:00
let zc_sec_header_wrapper = zc::PusTmSecHeader {
zc_header: sec_header_zc,
2023-07-11 22:12:17 +02:00
timestamp: &slice[current_idx..current_idx + timestamp_len],
2022-07-31 13:31:14 +02:00
};
current_idx += timestamp_len;
let raw_data = &slice[0..total_len];
2023-07-10 01:11:42 +02:00
let pus_tm = Self {
2022-12-05 01:41:35 +01:00
sp_header,
2022-07-31 13:31:14 +02:00
sec_header: PusTmSecondaryHeader::try_from(zc_sec_header_wrapper).unwrap(),
2023-07-10 01:11:42 +02:00
raw_data: &slice[0..total_len],
2023-12-03 15:45:11 +01:00
source_data: user_data_from_raw(current_idx, total_len, slice)?,
2023-07-10 01:11:42 +02:00
crc16: crc_from_raw_data(raw_data)?,
2022-07-31 13:31:14 +02:00
};
2023-07-10 01:11:42 +02:00
verify_crc16_ccitt_false_from_raw_to_pus_error(raw_data, pus_tm.crc16)?;
2022-07-31 13:31:14 +02:00
Ok((pus_tm, total_len))
}
2023-01-26 21:28:39 +01:00
2023-07-10 01:11:42 +02:00
pub fn len_packed(&self) -> usize {
self.sp_header.total_len()
}
2023-07-11 00:03:07 +02:00
pub fn source_data(&self) -> &[u8] {
self.user_data()
}
2023-07-11 22:12:17 +02:00
pub fn timestamp(&self) -> &[u8] {
2024-04-03 13:30:01 +02:00
self.sec_header.time_stamp
2023-07-10 01:11:42 +02:00
}
2023-08-16 14:02:33 +02:00
/// This function will return the slice [Self] was constructed from.
2023-07-10 23:29:55 +02:00
pub fn raw_data(&self) -> &[u8] {
2023-01-26 21:28:39 +01:00
self.raw_data
}
2022-07-31 13:31:14 +02:00
}
2023-07-10 01:11:42 +02:00
impl PartialEq for PusTmReader<'_> {
fn eq(&self, other: &Self) -> bool {
2023-12-06 15:17:03 +01:00
self.sec_header == other.sec_header
&& self.source_data == other.source_data
&& self.sp_header == other.sp_header
&& self.crc16 == other.crc16
2023-07-10 01:11:42 +02:00
}
}
impl CcsdsPacket for PusTmReader<'_> {
ccsds_impl!();
}
impl PusPacket for PusTmReader<'_> {
delegate!(to self.sec_header {
fn pus_version(&self) -> PusVersion;
fn service(&self) -> u8;
fn subservice(&self) -> u8;
});
2023-07-11 00:03:07 +02:00
fn user_data(&self) -> &[u8] {
2023-07-10 01:11:42 +02:00
self.source_data
}
fn crc16(&self) -> Option<u16> {
Some(self.crc16)
}
}
impl GenericPusTmSecondaryHeader for PusTmReader<'_> {
delegate!(to self.sec_header {
fn pus_version(&self) -> PusVersion;
fn service(&self) -> u8;
fn subservice(&self) -> u8;
fn dest_id(&self) -> u16;
fn msg_counter(&self) -> u16;
fn sc_time_ref_status(&self) -> u8;
});
}
impl IsPusTelemetry for PusTmReader<'_> {}
2024-03-29 14:06:52 +01:00
impl PartialEq<PusTmCreator<'_, '_>> for PusTmReader<'_> {
fn eq(&self, other: &PusTmCreator<'_, '_>) -> bool {
2023-07-10 01:11:42 +02:00
self.sp_header == other.sp_header
&& self.sec_header == other.sec_header
&& self.source_data == other.source_data
}
}
2024-03-29 14:06:52 +01:00
impl PartialEq<PusTmReader<'_>> for PusTmCreator<'_, '_> {
2023-07-10 01:11:42 +02:00
fn eq(&self, other: &PusTmReader<'_>) -> bool {
self.sp_header == other.sp_header
&& self.sec_header == other.sec_header
&& self.source_data == other.source_data
}
}
2023-07-05 19:07:31 +02:00
/// This is a helper class to update certain fields in a raw PUS telemetry packet directly in place.
2024-02-07 11:07:20 +01:00
/// This can be more efficient than creating a full [PusTmReader], modifying the fields and then
/// writing it back to another buffer.
2023-07-05 19:07:31 +02:00
///
/// Please note that the [Self::finish] method has to be called for the PUS TM CRC16 to be valid
/// after changing fields of the TM packet. Furthermore, the constructor of this class will not
2024-02-07 11:07:20 +01:00
/// do any checks except basic length checks to ensure that all relevant fields can be updated and
/// all methods can be called without a panic. If a full validity check of the PUS TM packet is
/// required, it is recommended to construct a full [PusTmReader] object from the raw bytestream
/// first.
2023-07-05 19:07:31 +02:00
pub struct PusTmZeroCopyWriter<'raw> {
raw_tm: &'raw mut [u8],
2024-02-07 11:07:20 +01:00
timestamp_len: usize,
2023-07-05 19:07:31 +02:00
}
impl<'raw> PusTmZeroCopyWriter<'raw> {
/// This function will not do any other checks on the raw data other than a length check
2024-02-07 11:07:20 +01:00
/// for all internal fields which can be updated.
///
/// It is the responsibility of the user to ensure the raw slice contains a valid telemetry
/// packet.
pub fn new(raw_tm: &'raw mut [u8], timestamp_len: usize) -> Option<Self> {
let raw_tm_len = raw_tm.len();
if raw_tm_len < CCSDS_HEADER_LEN + PUS_TM_MIN_SEC_HEADER_LEN + timestamp_len {
2023-07-05 19:07:31 +02:00
return None;
}
2024-02-07 11:07:20 +01:00
let sp_header = crate::zc::SpHeader::from_bytes(&raw_tm[0..CCSDS_HEADER_LEN]).unwrap();
if raw_tm_len < sp_header.total_len() {
return None;
}
let writer = Self {
raw_tm: &mut raw_tm[..sp_header.total_len()],
timestamp_len,
};
Some(writer)
2023-07-05 19:28:43 +02:00
}
2023-07-05 19:25:05 +02:00
/// Set the sequence count. Returns false and does not update the value if the passed value
/// exceeds [MAX_APID].
pub fn set_apid(&mut self, apid: u16) -> bool {
if apid > MAX_APID {
return false;
}
// Clear APID part of the raw packet ID
let updated_apid =
((((self.raw_tm[0] as u16) << 8) | self.raw_tm[1] as u16) & !MAX_APID) | apid;
self.raw_tm[0..2].copy_from_slice(&updated_apid.to_be_bytes());
true
}
2023-07-05 19:07:31 +02:00
/// This function sets the message counter in the PUS TM secondary header.
pub fn set_msg_count(&mut self, msg_count: u16) {
self.raw_tm[9..11].copy_from_slice(&msg_count.to_be_bytes());
}
/// This function sets the destination ID in the PUS TM secondary header.
pub fn set_destination_id(&mut self, dest_id: u16) {
self.raw_tm[11..13].copy_from_slice(&dest_id.to_be_bytes())
}
2024-02-07 11:07:20 +01:00
/// Helper API to generate the space packet header portion of the PUS TM from the raw memory.
#[inline]
pub fn sp_header(&self) -> crate::zc::SpHeader {
// Valid minimum length of packet was checked before.
crate::zc::SpHeader::from_bytes(&self.raw_tm[0..CCSDS_HEADER_LEN]).unwrap()
}
/// Helper API to generate the portion of the secondary header without a timestamp from the
/// raw memory.
#[inline]
pub fn sec_header_without_timestamp(&self) -> PusTmSecHeaderWithoutTimestamp {
// Valid minimum length of packet was checked before.
PusTmSecHeaderWithoutTimestamp::from_bytes(
&self.raw_tm[CCSDS_HEADER_LEN..CCSDS_HEADER_LEN + PUS_TM_MIN_SEC_HEADER_LEN],
)
.unwrap()
}
2023-07-05 19:07:31 +02:00
/// Set the sequence count. Returns false and does not update the value if the passed value
/// exceeds [MAX_SEQ_COUNT].
2023-07-05 19:26:22 +02:00
pub fn set_seq_count(&mut self, seq_count: u16) -> bool {
2023-07-05 19:07:31 +02:00
if seq_count > MAX_SEQ_COUNT {
return false;
}
let new_psc =
(u16::from_be_bytes(self.raw_tm[2..4].try_into().unwrap()) & 0xC000) | seq_count;
self.raw_tm[2..4].copy_from_slice(&new_psc.to_be_bytes());
true
}
/// This method has to be called after modifying fields to ensure the CRC16 of the telemetry
/// packet remains valid.
pub fn finish(self) {
let slice_len = self.raw_tm.len();
let crc16 = calc_pus_crc16(&self.raw_tm[..slice_len - 2]);
self.raw_tm[slice_len - 2..].copy_from_slice(&crc16.to_be_bytes());
}
}
2024-02-07 11:07:20 +01:00
impl CcsdsPacket for PusTmZeroCopyWriter<'_> {
#[inline]
fn ccsds_version(&self) -> u8 {
self.sp_header().ccsds_version()
}
#[inline]
fn packet_id(&self) -> crate::PacketId {
self.sp_header().packet_id()
}
#[inline]
fn psc(&self) -> crate::PacketSequenceCtrl {
self.sp_header().psc()
}
#[inline]
fn data_len(&self) -> u16 {
self.sp_header().data_len()
}
}
impl PusPacket for PusTmZeroCopyWriter<'_> {
#[inline]
fn pus_version(&self) -> PusVersion {
self.sec_header_without_timestamp().pus_version()
}
#[inline]
fn service(&self) -> u8 {
self.raw_tm[7]
}
#[inline]
fn subservice(&self) -> u8 {
self.raw_tm[8]
}
#[inline]
fn user_data(&self) -> &[u8] {
&self.raw_tm[CCSDS_HEADER_LEN + PUS_TM_MIN_SEC_HEADER_LEN + self.timestamp_len
..self.sp_header().total_len() - 2]
}
#[inline]
fn crc16(&self) -> Option<u16> {
Some(u16::from_be_bytes(
self.raw_tm[self.sp_header().total_len() - 2..self.sp_header().total_len()]
.try_into()
.unwrap(),
))
}
}
impl GenericPusTmSecondaryHeader for PusTmZeroCopyWriter<'_> {
delegate! {
to self.sec_header_without_timestamp() {
#[inline]
fn pus_version(&self) -> PusVersion;
#[inline]
fn sc_time_ref_status(&self) -> u8;
#[inline]
fn msg_counter(&self) -> u16;
#[inline]
fn dest_id(&self) -> u16;
}
}
#[inline]
fn service(&self) -> u8 {
PusPacket::service(self)
}
#[inline]
fn subservice(&self) -> u8 {
PusPacket::subservice(self)
}
}
2022-07-31 02:27:27 +02:00
#[cfg(test)]
2022-07-31 13:43:40 +02:00
mod tests {
2023-12-03 19:45:31 +01:00
use alloc::string::ToString;
2022-07-31 13:43:40 +02:00
use super::*;
2022-07-31 14:24:16 +02:00
use crate::ecss::PusVersion::PusC;
2024-03-18 15:14:40 +01:00
use crate::time::cds::CdsTime;
2023-12-06 15:17:03 +01:00
#[cfg(feature = "serde")]
use crate::time::CcsdsTimeProvider;
2022-07-31 13:43:40 +02:00
use crate::SpHeader;
2023-12-06 15:17:03 +01:00
#[cfg(feature = "serde")]
use postcard::{from_bytes, to_allocvec};
2022-07-31 13:43:40 +02:00
2024-02-07 11:07:20 +01:00
const DUMMY_DATA: &[u8] = &[0, 1, 2];
2023-07-10 01:11:42 +02:00
fn base_ping_reply_full_ctor(timestamp: &[u8]) -> PusTmCreator {
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
2023-11-24 16:15:46 +01:00
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
2023-12-03 19:45:31 +01:00
PusTmCreator::new_no_source_data(&mut sph, tm_header, true)
2022-07-31 13:43:40 +02:00
}
2024-02-07 11:07:20 +01:00
fn ping_reply_with_data(timestamp: &[u8]) -> PusTmCreator {
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
PusTmCreator::new(&mut sph, tm_header, DUMMY_DATA, true)
}
2022-07-31 13:43:40 +02:00
2024-03-29 14:06:52 +01:00
fn base_hk_reply<'a, 'b>(timestamp: &'a [u8], src_data: &'b [u8]) -> PusTmCreator<'a, 'b> {
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
2023-11-24 16:15:46 +01:00
let tc_header = PusTmSecondaryHeader::new_simple(3, 5, timestamp);
2023-12-03 19:45:31 +01:00
PusTmCreator::new(&mut sph, tc_header, src_data, true)
2022-08-01 01:08:06 +02:00
}
2023-01-16 11:56:25 +01:00
fn dummy_timestamp() -> &'static [u8] {
2023-11-24 16:15:46 +01:00
&[0, 1, 2, 3, 4, 5, 6]
2022-07-31 13:43:40 +02:00
}
2022-07-31 14:24:16 +02:00
2022-07-31 13:43:40 +02:00
#[test]
fn test_basic() {
2023-01-16 11:56:25 +01:00
let timestamp = dummy_timestamp();
2023-11-24 16:15:46 +01:00
let pus_tm = base_ping_reply_full_ctor(timestamp);
2023-01-16 11:56:25 +01:00
verify_ping_reply(&pus_tm, false, 22, dummy_timestamp());
2022-07-31 14:24:16 +02:00
}
2023-12-03 19:45:31 +01:00
#[test]
fn test_basic_simple_api() {
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
2024-03-18 15:14:40 +01:00
let time_provider = CdsTime::new_with_u16_days(0, 0);
2023-12-03 19:45:31 +01:00
let mut stamp_buf: [u8; 8] = [0; 8];
let pus_tm =
2023-12-07 13:49:59 +01:00
PusTmCreator::new_simple(&mut sph, 17, 2, &time_provider, &mut stamp_buf, None, true)
2023-12-03 19:45:31 +01:00
.unwrap();
verify_ping_reply(&pus_tm, false, 22, &[64, 0, 0, 0, 0, 0, 0]);
}
2022-07-31 14:24:16 +02:00
#[test]
fn test_serialization_no_source_data() {
2023-01-16 11:56:25 +01:00
let timestamp = dummy_timestamp();
2023-11-24 16:15:46 +01:00
let pus_tm = base_ping_reply_full_ctor(timestamp);
2022-07-31 14:24:16 +02:00
let mut buf: [u8; 32] = [0; 32];
2022-09-11 20:50:46 +02:00
let ser_len = pus_tm
.write_to_bytes(&mut buf)
.expect("Serialization failed");
2022-07-31 14:24:16 +02:00
assert_eq!(ser_len, 22);
2023-12-03 19:45:31 +01:00
verify_raw_ping_reply(pus_tm.crc16().unwrap(), &buf);
2022-08-01 01:08:06 +02:00
}
#[test]
fn test_serialization_with_source_data() {
let src_data = [1, 2, 3];
2023-01-16 11:56:25 +01:00
let hk_reply = base_hk_reply(dummy_timestamp(), &src_data);
2022-08-01 01:08:06 +02:00
let mut buf: [u8; 32] = [0; 32];
2022-09-11 20:50:46 +02:00
let ser_len = hk_reply
.write_to_bytes(&mut buf)
.expect("Serialization failed");
2022-08-01 01:08:06 +02:00
assert_eq!(ser_len, 25);
assert_eq!(buf[20], 1);
assert_eq!(buf[21], 2);
assert_eq!(buf[22], 3);
}
#[test]
fn test_setters() {
2023-01-16 11:56:25 +01:00
let timestamp = dummy_timestamp();
2023-11-24 16:34:06 +01:00
let mut pus_tm = base_ping_reply_full_ctor(timestamp);
2022-08-01 01:08:06 +02:00
pus_tm.set_sc_time_ref_status(0b1010);
pus_tm.set_dest_id(0x7fff);
pus_tm.set_msg_counter(0x1f1f);
assert_eq!(pus_tm.sc_time_ref_status(), 0b1010);
assert_eq!(pus_tm.dest_id(), 0x7fff);
assert_eq!(pus_tm.msg_counter(), 0x1f1f);
2022-08-05 00:24:29 +02:00
assert!(pus_tm.set_apid(0x7ff));
assert_eq!(pus_tm.apid(), 0x7ff);
2022-08-01 01:08:06 +02:00
}
2023-11-24 16:34:06 +01:00
#[test]
fn test_write_into_vec() {
let timestamp = dummy_timestamp();
let pus_tm = base_ping_reply_full_ctor(timestamp);
let tm_vec = pus_tm.to_vec().expect("Serialization failed");
assert_eq!(tm_vec.len(), 22);
let (tm_deserialized, size) =
PusTmReader::new(tm_vec.as_slice(), 7).expect("Deserialization failed");
assert_eq!(tm_vec.len(), size);
verify_ping_reply_with_reader(&tm_deserialized, false, 22, dummy_timestamp());
}
2022-08-01 01:08:06 +02:00
#[test]
fn test_deserialization_no_source_data() {
2023-01-16 11:56:25 +01:00
let timestamp = dummy_timestamp();
2023-11-24 16:34:06 +01:00
let pus_tm = base_ping_reply_full_ctor(timestamp);
2022-08-01 01:08:06 +02:00
let mut buf: [u8; 32] = [0; 32];
2022-09-11 20:50:46 +02:00
let ser_len = pus_tm
.write_to_bytes(&mut buf)
.expect("Serialization failed");
2022-08-01 01:08:06 +02:00
assert_eq!(ser_len, 22);
2023-07-10 01:11:42 +02:00
let (tm_deserialized, size) = PusTmReader::new(&buf, 7).expect("Deserialization failed");
2022-08-01 01:08:06 +02:00
assert_eq!(ser_len, size);
2023-12-03 19:45:31 +01:00
assert_eq!(tm_deserialized.user_data(), tm_deserialized.source_data());
assert_eq!(tm_deserialized.raw_data(), &buf[..ser_len]);
assert_eq!(tm_deserialized.crc16().unwrap(), pus_tm.crc16().unwrap());
2023-07-10 01:11:42 +02:00
verify_ping_reply_with_reader(&tm_deserialized, false, 22, dummy_timestamp());
2022-08-01 01:08:06 +02:00
}
2023-12-03 19:45:31 +01:00
#[test]
fn test_deserialization_faulty_crc() {
let timestamp = dummy_timestamp();
let pus_tm = base_ping_reply_full_ctor(timestamp);
let mut buf: [u8; 32] = [0; 32];
let ser_len = pus_tm
.write_to_bytes(&mut buf)
.expect("Serialization failed");
assert_eq!(ser_len, 22);
buf[ser_len - 2] = 0;
buf[ser_len - 1] = 0;
let tm_error = PusTmReader::new(&buf, 7);
assert!(tm_error.is_err());
let tm_error = tm_error.unwrap_err();
if let PusError::ChecksumFailure(crc) = tm_error {
assert_eq!(crc, 0);
assert_eq!(
tm_error.to_string(),
"checksum verification for crc16 0x0000 failed"
);
}
}
2022-08-01 01:08:06 +02:00
#[test]
fn test_manual_field_update() {
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
2023-01-16 11:56:25 +01:00
let tc_header = PusTmSecondaryHeader::new_simple(17, 2, dummy_timestamp());
2023-12-03 19:45:31 +01:00
let mut tm = PusTmCreator::new_no_source_data(&mut sph, tc_header, false);
2022-08-01 01:08:06 +02:00
tm.calc_crc_on_serialization = false;
assert_eq!(tm.data_len(), 0x00);
let mut buf: [u8; 32] = [0; 32];
tm.update_ccsds_data_len();
assert_eq!(tm.data_len(), 15);
tm.calc_own_crc16();
2022-09-11 20:50:46 +02:00
let res = tm.write_to_bytes(&mut buf);
2022-08-01 01:08:06 +02:00
assert!(res.is_ok());
tm.sp_header.data_len = 0;
tm.update_packet_fields();
assert_eq!(tm.data_len(), 15);
}
#[test]
fn test_target_buf_too_small() {
2023-01-16 11:56:25 +01:00
let timestamp = dummy_timestamp();
2023-11-24 16:34:06 +01:00
let pus_tm = base_ping_reply_full_ctor(timestamp);
2022-08-01 01:08:06 +02:00
let mut buf: [u8; 16] = [0; 16];
2022-09-11 20:50:46 +02:00
let res = pus_tm.write_to_bytes(&mut buf);
2022-08-01 01:08:06 +02:00
assert!(res.is_err());
let error = res.unwrap_err();
2024-03-25 13:42:18 +01:00
if let ByteConversionError::ToSliceTooSmall { found, expected } = error {
assert_eq!(expected, 22);
assert_eq!(found, 16);
} else {
panic!("Invalid error {:?}", error);
2022-08-01 01:08:06 +02:00
}
}
#[test]
#[cfg(feature = "alloc")]
fn test_append_to_vec() {
2023-01-16 11:56:25 +01:00
let timestamp = dummy_timestamp();
2023-11-24 16:15:46 +01:00
let pus_tm = base_ping_reply_full_ctor(timestamp);
2022-08-01 01:08:06 +02:00
let mut vec = Vec::new();
let res = pus_tm.append_to_vec(&mut vec);
assert!(res.is_ok());
assert_eq!(res.unwrap(), 22);
2023-12-03 19:45:31 +01:00
verify_raw_ping_reply(pus_tm.crc16().unwrap(), vec.as_slice());
2022-08-01 01:08:06 +02:00
}
#[test]
#[cfg(feature = "alloc")]
fn test_append_to_vec_with_src_data() {
let src_data = [1, 2, 3];
2023-01-16 11:56:25 +01:00
let hk_reply = base_hk_reply(dummy_timestamp(), &src_data);
2022-08-01 01:08:06 +02:00
let mut vec = Vec::new();
vec.push(4);
let res = hk_reply.append_to_vec(&mut vec);
assert!(res.is_ok());
assert_eq!(res.unwrap(), 25);
assert_eq!(vec.len(), 26);
}
2023-12-03 19:45:31 +01:00
fn verify_raw_ping_reply(crc16: u16, buf: &[u8]) {
2022-08-01 00:20:11 +02:00
// Secondary header is set -> 0b0000_1001 , APID occupies last bit of first byte
assert_eq!(buf[0], 0x09);
// Rest of APID 0x123
assert_eq!(buf[1], 0x23);
// Unsegmented is the default, and first byte of 0x234 occupies this byte as well
assert_eq!(buf[2], 0xc2);
assert_eq!(buf[3], 0x34);
assert_eq!(((buf[4] as u16) << 8) | buf[5] as u16, 15);
// SC time ref status is 0
assert_eq!(buf[6], (PusC as u8) << 4);
assert_eq!(buf[7], 17);
assert_eq!(buf[8], 2);
// MSG counter 0
assert_eq!(buf[9], 0x00);
assert_eq!(buf[10], 0x00);
// Destination ID
assert_eq!(buf[11], 0x00);
assert_eq!(buf[12], 0x00);
// Timestamp
2023-01-16 11:56:25 +01:00
assert_eq!(&buf[13..20], dummy_timestamp());
2022-08-01 00:20:11 +02:00
let mut digest = CRC_CCITT_FALSE.digest();
digest.update(&buf[0..20]);
2023-12-03 19:45:31 +01:00
let crc16_calced = digest.finalize();
2022-08-01 00:20:11 +02:00
assert_eq!(((crc16 >> 8) & 0xff) as u8, buf[20]);
assert_eq!((crc16 & 0xff) as u8, buf[21]);
2023-12-03 19:45:31 +01:00
assert_eq!(crc16, crc16_calced);
2022-07-31 14:24:16 +02:00
}
2022-08-01 01:08:06 +02:00
fn verify_ping_reply(
2023-07-10 01:11:42 +02:00
tm: &PusTmCreator,
has_user_data: bool,
exp_full_len: usize,
exp_timestamp: &[u8],
) {
2023-11-24 16:15:46 +01:00
assert_eq!(tm.len_written(), exp_full_len);
2023-07-11 22:12:17 +02:00
assert_eq!(tm.timestamp(), exp_timestamp);
2023-12-03 19:45:31 +01:00
assert_eq!(tm.source_data(), tm.user_data());
2023-07-10 01:11:42 +02:00
verify_ping_reply_generic(tm, has_user_data, exp_full_len);
}
fn verify_ping_reply_with_reader(
tm: &PusTmReader,
2022-07-31 14:24:16 +02:00
has_user_data: bool,
exp_full_len: usize,
2023-01-16 11:56:25 +01:00
exp_timestamp: &[u8],
2023-07-10 01:11:42 +02:00
) {
assert_eq!(tm.len_packed(), exp_full_len);
2023-07-11 22:12:17 +02:00
assert_eq!(tm.timestamp(), exp_timestamp);
2023-07-10 01:11:42 +02:00
verify_ping_reply_generic(tm, has_user_data, exp_full_len);
}
fn verify_ping_reply_generic(
tm: &(impl CcsdsPacket + GenericPusTmSecondaryHeader + PusPacket),
has_user_data: bool,
exp_full_len: usize,
2022-07-31 14:24:16 +02:00
) {
2022-07-31 13:43:40 +02:00
assert!(tm.is_tm());
2022-07-31 14:24:16 +02:00
assert_eq!(PusPacket::service(tm), 17);
2023-12-03 19:45:31 +01:00
assert_eq!(GenericPusTmSecondaryHeader::service(tm), 17);
2022-07-31 14:24:16 +02:00
assert_eq!(PusPacket::subservice(tm), 2);
2023-12-03 19:45:31 +01:00
assert_eq!(GenericPusTmSecondaryHeader::subservice(tm), 2);
2022-07-31 13:43:40 +02:00
assert!(tm.sec_header_flag());
if has_user_data {
2023-07-11 00:03:07 +02:00
assert!(!tm.user_data().is_empty());
2022-07-31 13:43:40 +02:00
}
2022-07-31 14:24:16 +02:00
assert_eq!(PusPacket::pus_version(tm), PusC);
2022-08-01 00:20:11 +02:00
assert_eq!(tm.apid(), 0x123);
assert_eq!(tm.seq_count(), 0x234);
2023-12-03 19:45:31 +01:00
assert_eq!(PusPacket::pus_version(tm), PusVersion::PusC);
assert_eq!(
GenericPusTmSecondaryHeader::pus_version(tm),
PusVersion::PusC
);
2022-07-31 14:24:16 +02:00
assert_eq!(tm.data_len(), exp_full_len as u16 - 7);
assert_eq!(tm.dest_id(), 0x0000);
assert_eq!(tm.msg_counter(), 0x0000);
assert_eq!(tm.sc_time_ref_status(), 0b0000);
2022-07-31 13:43:40 +02:00
}
2023-01-26 19:24:41 +01:00
#[test]
2023-01-26 21:11:03 +01:00
fn partial_eq_pus_tm() {
2023-01-26 19:24:41 +01:00
let timestamp = dummy_timestamp();
2023-01-26 21:11:03 +01:00
let pus_tm_1 = base_ping_reply_full_ctor(timestamp);
let pus_tm_2 = base_ping_reply_full_ctor(timestamp);
assert_eq!(pus_tm_1, pus_tm_2);
2023-01-26 19:24:41 +01:00
}
#[test]
fn partial_eq_serialized_vs_derialized() {
let timestamp = dummy_timestamp();
let pus_tm = base_ping_reply_full_ctor(timestamp);
let mut buf = [0; 32];
2023-01-26 21:11:03 +01:00
pus_tm.write_to_bytes(&mut buf).unwrap();
2023-07-10 01:11:42 +02:00
assert_eq!(pus_tm, PusTmReader::new(&buf, timestamp.len()).unwrap().0);
2023-01-26 19:24:41 +01:00
}
2023-07-05 19:07:31 +02:00
#[test]
fn test_zero_copy_writer() {
let ping_tm = base_ping_reply_full_ctor(dummy_timestamp());
let mut buf: [u8; 64] = [0; 64];
let tm_size = ping_tm
.write_to_bytes(&mut buf)
.expect("writing PUS ping TM failed");
2024-02-07 11:07:20 +01:00
let mut writer = PusTmZeroCopyWriter::new(&mut buf[..tm_size], 7)
2023-07-05 19:07:31 +02:00
.expect("Creating zero copy writer failed");
writer.set_destination_id(55);
writer.set_msg_count(100);
2023-07-06 01:24:40 +02:00
writer.set_seq_count(MAX_SEQ_COUNT);
2023-07-05 19:25:05 +02:00
writer.set_apid(MAX_APID);
2023-12-03 19:45:31 +01:00
assert!(!writer.set_apid(MAX_APID + 1));
assert!(!writer.set_apid(MAX_SEQ_COUNT + 1));
2023-07-05 19:25:05 +02:00
writer.finish();
2023-07-05 19:07:31 +02:00
// This performs all necessary checks, including the CRC check.
let (tm_read_back, tm_size_read_back) =
2023-07-11 00:41:35 +02:00
PusTmReader::new(&buf, 7).expect("Re-creating PUS TM failed");
2023-07-05 19:07:31 +02:00
assert_eq!(tm_size_read_back, tm_size);
assert_eq!(tm_read_back.msg_counter(), 100);
assert_eq!(tm_read_back.dest_id(), 55);
2023-07-05 19:25:05 +02:00
assert_eq!(tm_read_back.seq_count(), MAX_SEQ_COUNT);
assert_eq!(tm_read_back.apid(), MAX_APID);
2023-07-05 19:07:31 +02:00
}
2023-12-03 19:45:31 +01:00
2024-02-07 11:07:20 +01:00
#[test]
fn test_zero_copy_writer_ccsds_api() {
let ping_tm = base_ping_reply_full_ctor(dummy_timestamp());
let mut buf: [u8; 64] = [0; 64];
let tm_size = ping_tm
.write_to_bytes(&mut buf)
.expect("writing PUS ping TM failed");
let mut writer = PusTmZeroCopyWriter::new(&mut buf[..tm_size], 7)
.expect("Creating zero copy writer failed");
writer.set_destination_id(55);
writer.set_msg_count(100);
writer.set_seq_count(MAX_SEQ_COUNT);
writer.set_apid(MAX_APID);
assert_eq!(PusPacket::service(&writer), 17);
assert_eq!(PusPacket::subservice(&writer), 2);
assert_eq!(writer.apid(), MAX_APID);
assert_eq!(writer.seq_count(), MAX_SEQ_COUNT);
}
#[test]
fn test_zero_copy_pus_api() {
let ping_tm = ping_reply_with_data(dummy_timestamp());
let mut buf: [u8; 64] = [0; 64];
let tm_size = ping_tm
.write_to_bytes(&mut buf)
.expect("writing PUS ping TM failed");
let crc16_raw = u16::from_be_bytes(buf[tm_size - 2..tm_size].try_into().unwrap());
let mut writer = PusTmZeroCopyWriter::new(&mut buf[..tm_size], 7)
.expect("Creating zero copy writer failed");
writer.set_destination_id(55);
writer.set_msg_count(100);
writer.set_seq_count(MAX_SEQ_COUNT);
writer.set_apid(MAX_APID);
assert_eq!(PusPacket::service(&writer), 17);
assert_eq!(PusPacket::subservice(&writer), 2);
assert_eq!(writer.dest_id(), 55);
assert_eq!(writer.msg_counter(), 100);
assert_eq!(writer.sec_header_without_timestamp().dest_id(), 55);
assert_eq!(writer.sec_header_without_timestamp().msg_counter(), 100);
assert_eq!(writer.user_data(), DUMMY_DATA);
// Need to check crc16 before finish, because finish will update the CRC.
let crc16 = writer.crc16();
assert!(crc16.is_some());
assert_eq!(crc16.unwrap(), crc16_raw);
writer.finish();
}
2023-12-03 19:45:31 +01:00
#[test]
fn test_sec_header_without_stamp() {
let sec_header = PusTmSecondaryHeader::new_simple_no_timestamp(17, 1);
2024-04-03 13:30:01 +02:00
assert_eq!(sec_header.time_stamp, &[]);
2023-12-03 19:45:31 +01:00
}
#[test]
fn test_reader_partial_eq() {
let timestamp = dummy_timestamp();
let pus_tm = base_ping_reply_full_ctor(timestamp);
let mut buf = [0; 32];
pus_tm.write_to_bytes(&mut buf).unwrap();
let (tm_0, _) = PusTmReader::new(&buf, timestamp.len()).unwrap();
let (tm_1, _) = PusTmReader::new(&buf, timestamp.len()).unwrap();
assert_eq!(tm_0, tm_1);
}
#[test]
fn test_reader_buf_too_small_2() {
let timestamp = dummy_timestamp();
let pus_tm = base_ping_reply_full_ctor(timestamp);
let mut buf = [0; 32];
let written = pus_tm.write_to_bytes(&mut buf).unwrap();
let tm_error = PusTmReader::new(
&buf[0..PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA + 1],
timestamp.len(),
);
assert!(tm_error.is_err());
let tm_error = tm_error.unwrap_err();
if let PusError::ByteConversion(ByteConversionError::FromSliceTooSmall {
found,
expected,
}) = tm_error
{
assert_eq!(found, PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA + 1);
assert_eq!(expected, written);
} else {
panic!("unexpected error {tm_error}")
}
}
#[test]
fn test_reader_buf_too_small() {
let timestamp = dummy_timestamp();
let pus_tm = base_ping_reply_full_ctor(timestamp);
let mut buf = [0; 32];
pus_tm.write_to_bytes(&mut buf).unwrap();
let tm_error = PusTmReader::new(&buf[0..5], timestamp.len());
assert!(tm_error.is_err());
let tm_error = tm_error.unwrap_err();
if let PusError::ByteConversion(ByteConversionError::FromSliceTooSmall {
found,
expected,
}) = tm_error
{
assert_eq!(found, 5);
assert_eq!(expected, PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA);
} else {
panic!("unexpected error {tm_error}")
}
}
2023-12-06 15:17:03 +01:00
#[test]
#[cfg(feature = "serde")]
fn test_serialization_creator_serde() {
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
2024-03-18 15:14:40 +01:00
let time_provider = CdsTime::new_with_u16_days(0, 0);
2023-12-06 15:17:03 +01:00
let mut stamp_buf: [u8; 8] = [0; 8];
let pus_tm =
2023-12-07 13:49:59 +01:00
PusTmCreator::new_simple(&mut sph, 17, 2, &time_provider, &mut stamp_buf, None, true)
2023-12-06 15:17:03 +01:00
.unwrap();
let output = to_allocvec(&pus_tm).unwrap();
let output_converted_back: PusTmCreator = from_bytes(&output).unwrap();
assert_eq!(output_converted_back, pus_tm);
}
#[test]
#[cfg(feature = "serde")]
fn test_serialization_reader_serde() {
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
2024-03-18 15:14:40 +01:00
let time_provider = CdsTime::new_with_u16_days(0, 0);
2023-12-06 15:17:03 +01:00
let mut stamp_buf: [u8; 8] = [0; 8];
let pus_tm =
2023-12-07 13:49:59 +01:00
PusTmCreator::new_simple(&mut sph, 17, 2, &time_provider, &mut stamp_buf, None, true)
2023-12-06 15:17:03 +01:00
.unwrap();
let pus_tm_vec = pus_tm.to_vec().unwrap();
let (tm_reader, _) = PusTmReader::new(&pus_tm_vec, time_provider.len_as_bytes()).unwrap();
let output = to_allocvec(&tm_reader).unwrap();
let output_converted_back: PusTmReader = from_bytes(&output).unwrap();
assert_eq!(output_converted_back, tm_reader);
}
2022-07-31 13:43:40 +02:00
}