sat-rs/satrs-core/src/pus/mod.rs

513 lines
17 KiB
Rust
Raw Normal View History

2023-01-25 10:52:24 +01:00
//! # PUS support modules
2023-07-06 01:14:01 +02:00
//!
//! This module contains structures to make working with the PUS C standard easier.
//! The satrs-example application contains various usage examples of these components.
2023-07-08 14:57:11 +02:00
use crate::pus::verification::TcStateToken;
use crate::SenderId;
#[cfg(feature = "alloc")]
use downcast_rs::{impl_downcast, Downcast};
#[cfg(feature = "alloc")]
use dyn_clone::DynClone;
use spacepackets::ecss::PusError;
2023-07-03 00:42:20 +02:00
use spacepackets::tc::PusTc;
use spacepackets::time::TimestampError;
use spacepackets::tm::PusTm;
use spacepackets::{ByteConversionError, SizeMissmatch};
pub mod event;
pub mod event_man;
2023-07-05 14:25:51 +02:00
pub mod event_srv;
pub mod hk;
2023-02-15 11:05:32 +01:00
pub mod mode;
2023-07-05 11:25:23 +02:00
pub mod scheduler;
pub mod scheduler_srv;
2023-01-21 12:19:05 +01:00
#[cfg(feature = "std")]
2023-07-05 11:25:23 +02:00
pub mod test;
pub mod verification;
2023-01-25 10:52:24 +01:00
#[cfg(feature = "alloc")]
pub use alloc_mod::*;
2023-07-08 14:57:11 +02:00
use crate::pool::StoreAddr;
2023-02-27 17:00:21 +01:00
#[cfg(feature = "std")]
pub use std_mod::*;
2023-07-08 14:57:11 +02:00
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum PusTmWrapper<'tm> {
InStore(StoreAddr),
Direct(PusTm<'tm>),
}
impl From<StoreAddr> for PusTmWrapper<'_> {
fn from(value: StoreAddr) -> Self {
Self::InStore(value)
}
}
impl<'tm> From<PusTm<'tm>> for PusTmWrapper<'tm> {
fn from(value: PusTm<'tm>) -> Self {
Self::Direct(value)
}
}
#[derive(Debug, Clone)]
2023-07-03 00:42:20 +02:00
pub enum EcssTmtcErrorWithSend<E> {
/// Errors related to sending the telemetry to a TMTC recipient
SendError(E),
2023-07-03 00:42:20 +02:00
EcssTmtcError(EcssTmtcError),
}
2023-07-03 00:42:20 +02:00
impl<E> From<EcssTmtcError> for EcssTmtcErrorWithSend<E> {
fn from(value: EcssTmtcError) -> Self {
Self::EcssTmtcError(value)
}
}
2023-02-27 17:00:21 +01:00
/// Generic error type for PUS TM handling.
#[derive(Debug, Clone)]
2023-07-03 00:42:20 +02:00
pub enum EcssTmtcError {
/// Errors related to the time stamp format of the telemetry
2023-07-08 14:57:11 +02:00
Timestamp(TimestampError),
/// Errors related to byte conversion, for example insufficient buffer size for given data
2023-07-08 14:57:11 +02:00
ByteConversion(ByteConversionError),
/// Errors related to PUS packet format
2023-07-08 14:57:11 +02:00
Pus(PusError),
}
2023-07-03 00:42:20 +02:00
impl From<PusError> for EcssTmtcError {
fn from(e: PusError) -> Self {
2023-07-08 14:57:11 +02:00
EcssTmtcError::Pus(e)
}
}
2023-07-03 00:42:20 +02:00
impl From<ByteConversionError> for EcssTmtcError {
fn from(e: ByteConversionError) -> Self {
2023-07-08 14:57:11 +02:00
EcssTmtcError::ByteConversion(e)
}
}
2023-07-03 00:42:20 +02:00
pub trait EcssSender: Send {
/// Each sender can have an ID associated with it
fn id(&self) -> SenderId;
fn name(&self) -> &'static str {
"unset"
}
}
2023-07-03 00:42:20 +02:00
/// Generic trait for a user supplied sender object.
///
/// This sender object is responsible for sending PUS telemetry to a TM sink.
pub trait EcssTmSenderCore: EcssSender {
type Error;
2023-07-08 14:57:11 +02:00
fn send_tm(&self, tm: PusTmWrapper) -> Result<(), Self::Error>;
2023-07-03 00:42:20 +02:00
}
/// Generic trait for a user supplied sender object.
///
2023-07-08 14:57:11 +02:00
/// This sender object is responsible for sending PUS telecommands to a TC recipient. Each
/// telecommand can optionally have a token which contains its verification state.
2023-07-03 00:42:20 +02:00
pub trait EcssTcSenderCore: EcssSender {
type Error;
2023-07-08 14:57:11 +02:00
fn send_tc(&self, tc: PusTc, token: Option<TcStateToken>) -> Result<(), Self::Error>;
2023-07-03 00:42:20 +02:00
}
#[cfg(feature = "alloc")]
2023-01-25 10:52:24 +01:00
mod alloc_mod {
use super::*;
/// Extension trait for [EcssTmSenderCore].
///
/// It provides additional functionality, for example by implementing the [Downcast] trait
/// and the [DynClone] trait.
///
/// [Downcast] is implemented to allow passing the sender as a boxed trait object and still
/// retrieve the concrete type at a later point.
///
/// [DynClone] allows cloning the trait object as long as the boxed object implements
/// [Clone].
2023-01-25 10:52:24 +01:00
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
pub trait EcssTmSender: EcssTmSenderCore + Downcast + DynClone {}
/// Blanket implementation for all types which implement [EcssTmSenderCore] and are clonable.
impl<T> EcssTmSender for T where T: EcssTmSenderCore + Clone + 'static {}
dyn_clone::clone_trait_object!(<T> EcssTmSender<Error=T>);
impl_downcast!(EcssTmSender assoc Error);
2023-07-03 00:42:20 +02:00
/// Extension trait for [EcssTcSenderCore].
///
/// It provides additional functionality, for example by implementing the [Downcast] trait
/// and the [DynClone] trait.
///
/// [Downcast] is implemented to allow passing the sender as a boxed trait object and still
/// retrieve the concrete type at a later point.
///
/// [DynClone] allows cloning the trait object as long as the boxed object implements
/// [Clone].
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
pub trait EcssTcSender: EcssTcSenderCore + Downcast + DynClone {}
/// Blanket implementation for all types which implement [EcssTcSenderCore] and are clonable.
impl<T> EcssTcSender for T where T: EcssTcSenderCore + Clone + 'static {}
dyn_clone::clone_trait_object!(<T> EcssTcSender<Error=T>);
impl_downcast!(EcssTcSender assoc Error);
}
2023-02-27 17:00:21 +01:00
#[cfg(feature = "std")]
pub mod std_mod {
use crate::pool::{ShareablePoolProvider, SharedPool, StoreAddr, StoreError};
2023-07-05 11:25:23 +02:00
use crate::pus::verification::{
2023-07-05 21:08:04 +02:00
StdVerifReporterWithSender, TcStateAccepted, VerificationToken,
2023-07-05 11:25:23 +02:00
};
2023-07-08 14:57:11 +02:00
use crate::pus::{EcssSender, EcssTmSenderCore, PusTmWrapper};
2023-07-05 11:25:23 +02:00
use crate::tmtc::tm_helper::SharedTmStore;
use crate::SenderId;
2023-02-27 17:00:21 +01:00
use alloc::vec::Vec;
2023-07-05 21:08:04 +02:00
use spacepackets::ecss::{PusError, SerializablePusPacket};
2023-07-05 11:25:23 +02:00
use spacepackets::time::cds::TimeProvider;
use spacepackets::time::{StdTimestampError, TimeWriter};
2023-07-06 00:49:18 +02:00
use std::cell::RefCell;
2023-07-05 21:08:04 +02:00
use std::format;
2023-07-05 11:25:23 +02:00
use std::string::String;
2023-02-27 17:00:21 +01:00
use std::sync::{mpsc, RwLockWriteGuard};
2023-07-05 11:25:23 +02:00
use thiserror::Error;
2023-02-27 17:00:21 +01:00
2023-07-05 11:25:23 +02:00
#[derive(Debug, Clone, Error)]
2023-07-08 14:57:11 +02:00
pub enum MpscTmInStoreSenderError {
2023-07-05 11:25:23 +02:00
#[error("RwGuard lock error")]
2023-07-08 14:57:11 +02:00
StoreLock,
2023-07-05 11:25:23 +02:00
#[error("Generic PUS error: {0}")]
2023-07-08 14:57:11 +02:00
Pus(#[from] PusError),
2023-07-05 11:25:23 +02:00
#[error("Generic store error: {0}")]
2023-07-08 14:57:11 +02:00
Store(#[from] StoreError),
#[error("MPSC channel send error: {0}")]
Send(#[from] mpsc::SendError<StoreAddr>),
2023-07-05 11:25:23 +02:00
#[error("RX handle has disconnected")]
2023-07-08 14:57:11 +02:00
RxDisconnected,
2023-02-27 17:00:21 +01:00
}
#[derive(Clone)]
2023-07-08 14:57:11 +02:00
pub struct MpscTmInStoreSender {
id: SenderId,
name: &'static str,
2023-02-27 17:00:21 +01:00
store_helper: SharedPool,
sender: mpsc::Sender<StoreAddr>,
pub ignore_poison_errors: bool,
}
2023-07-08 14:57:11 +02:00
impl EcssSender for MpscTmInStoreSender {
fn id(&self) -> SenderId {
self.id
}
2023-07-03 00:42:20 +02:00
fn name(&self) -> &'static str {
self.name
}
}
2023-07-08 14:57:11 +02:00
impl MpscTmInStoreSender {
pub fn send_direct_tm(
&self,
2023-07-03 01:33:13 +02:00
tmtc: impl SerializablePusPacket,
2023-07-08 14:57:11 +02:00
) -> Result<(), MpscTmInStoreSenderError> {
2023-02-27 17:00:21 +01:00
let operation = |mut store: RwLockWriteGuard<ShareablePoolProvider>| {
2023-07-03 01:33:13 +02:00
let (addr, slice) = store.free_element(tmtc.len_packed())?;
tmtc.write_to_bytes(slice)?;
2023-02-27 17:00:21 +01:00
self.sender.send(addr)?;
Ok(())
};
match self.store_helper.write() {
Ok(pool) => operation(pool),
Err(e) => {
if self.ignore_poison_errors {
operation(e.into_inner())
} else {
2023-07-08 14:57:11 +02:00
Err(MpscTmInStoreSenderError::StoreLock)
2023-02-27 17:00:21 +01:00
}
}
}
}
2023-07-03 00:42:20 +02:00
}
2023-07-08 14:57:11 +02:00
impl EcssTmSenderCore for MpscTmInStoreSender {
type Error = MpscTmInStoreSenderError;
2023-07-03 01:33:13 +02:00
2023-07-08 14:57:11 +02:00
fn send_tm(&self, tm: PusTmWrapper) -> Result<(), Self::Error> {
match tm {
PusTmWrapper::InStore(addr) => self
.sender
.send(addr)
.map_err(MpscTmInStoreSenderError::Send),
PusTmWrapper::Direct(tm) => self.send_direct_tm(tm),
}
}
2023-02-27 17:00:21 +01:00
}
2023-07-08 14:57:11 +02:00
impl MpscTmInStoreSender {
pub fn new(
id: SenderId,
name: &'static str,
store_helper: SharedPool,
sender: mpsc::Sender<StoreAddr>,
) -> Self {
2023-02-27 17:00:21 +01:00
Self {
id,
name,
2023-02-27 17:00:21 +01:00
store_helper,
sender,
ignore_poison_errors: false,
}
}
}
2023-07-08 14:57:11 +02:00
#[derive(Debug, Clone, Error)]
pub enum MpscTmAsVecSenderError {
#[error("Generic PUS error: {0}")]
Pus(#[from] PusError),
#[error("MPSC channel send error: {0}")]
Send(#[from] mpsc::SendError<Vec<u8>>),
#[error("can not handle store addresses")]
CantSendAddr(StoreAddr),
#[error("RX handle has disconnected")]
RxDisconnected,
2023-02-27 17:00:21 +01:00
}
2023-07-08 14:57:11 +02:00
/// This class can be used if frequent heap allocations during run-time are not an issue.
/// PUS TM packets will be sent around as [Vec]s. Please note that the current implementation
/// of this class can not deal with store addresses, so it is assumed that is is always
/// going to be called with direct packets.
#[derive(Clone)]
2023-02-27 17:00:21 +01:00
pub struct MpscTmAsVecSender {
id: SenderId,
2023-02-27 17:00:21 +01:00
sender: mpsc::Sender<Vec<u8>>,
name: &'static str,
2023-02-27 17:00:21 +01:00
}
impl MpscTmAsVecSender {
pub fn new(id: u32, name: &'static str, sender: mpsc::Sender<Vec<u8>>) -> Self {
Self { id, sender, name }
2023-02-27 17:00:21 +01:00
}
}
2023-07-03 00:42:20 +02:00
impl EcssSender for MpscTmAsVecSender {
fn id(&self) -> SenderId {
self.id
}
2023-07-03 00:42:20 +02:00
fn name(&self) -> &'static str {
self.name
}
}
impl EcssTmSenderCore for MpscTmAsVecSender {
2023-07-08 14:57:11 +02:00
type Error = MpscTmAsVecSenderError;
fn send_tm(&self, tm: PusTmWrapper) -> Result<(), Self::Error> {
match tm {
PusTmWrapper::InStore(addr) => Err(MpscTmAsVecSenderError::CantSendAddr(addr)),
PusTmWrapper::Direct(tm) => {
let mut vec = Vec::new();
tm.append_to_vec(&mut vec)
.map_err(MpscTmAsVecSenderError::Pus)?;
self.sender
.send(vec)
.map_err(MpscTmAsVecSenderError::Send)?;
Ok(())
}
}
2023-02-27 17:00:21 +01:00
}
}
2023-07-05 11:25:23 +02:00
#[derive(Debug, Clone, Error)]
pub enum PusPacketHandlingError {
#[error("Generic PUS error: {0}")]
PusError(#[from] PusError),
#[error("Wrong service number {0} for packet handler")]
WrongService(u8),
2023-07-05 14:25:51 +02:00
#[error("Invalid subservice {0}")]
InvalidSubservice(u8),
2023-07-05 11:25:23 +02:00
#[error("Not enough application data available: {0}")]
NotEnoughAppData(String),
2023-07-06 01:14:01 +02:00
#[error("Invalid application data")]
InvalidAppData(String),
2023-07-05 11:25:23 +02:00
#[error("Generic store error: {0}")]
StoreError(#[from] StoreError),
2023-07-05 14:25:51 +02:00
#[error("Error with the pool RwGuard: {0}")]
2023-07-05 11:25:23 +02:00
RwGuardError(String),
2023-07-05 14:25:51 +02:00
#[error("MQ send error: {0}")]
SendError(String),
#[error("TX message queue side has disconnected")]
2023-07-05 11:25:23 +02:00
QueueDisconnected,
#[error("Other error {0}")]
OtherError(String),
}
#[derive(Debug, Clone, Error)]
pub enum PartialPusHandlingError {
#[error("Generic timestamp generation error")]
2023-07-08 13:37:27 +02:00
Time(StdTimestampError),
2023-07-05 11:25:23 +02:00
#[error("Error sending telemetry: {0}")]
2023-07-08 13:37:27 +02:00
TmSend(String),
2023-07-05 11:25:23 +02:00
#[error("Error sending verification message")]
2023-07-08 13:37:27 +02:00
Verification,
2023-07-05 11:25:23 +02:00
}
2023-07-06 01:14:01 +02:00
/// Generic result type for handlers which can process PUS packets.
2023-07-05 11:25:23 +02:00
#[derive(Debug, Clone)]
pub enum PusPacketHandlerResult {
RequestHandled,
RequestHandledPartialSuccess(PartialPusHandlingError),
2023-07-05 14:25:51 +02:00
SubserviceNotImplemented(u8, VerificationToken<TcStateAccepted>),
2023-07-05 11:58:43 +02:00
CustomSubservice(u8, VerificationToken<TcStateAccepted>),
2023-07-05 11:25:23 +02:00
Empty,
}
impl From<PartialPusHandlingError> for PusPacketHandlerResult {
fn from(value: PartialPusHandlingError) -> Self {
Self::RequestHandledPartialSuccess(value)
}
}
2023-07-06 01:14:01 +02:00
/// Generic abstraction for a telecommand being sent around after is has been accepted.
/// The actual telecommand is stored inside a pre-allocated pool structure.
2023-07-05 11:25:23 +02:00
pub type AcceptedTc = (StoreAddr, VerificationToken<TcStateAccepted>);
2023-07-06 01:14:01 +02:00
/// Base class for handlers which can handle PUS TC packets. Right now, the message queue
/// backend is constrained to [mpsc::channel]s and the verification reporter
/// is constrained to the [StdVerifReporterWithSender].
2023-07-05 11:25:23 +02:00
pub struct PusServiceBase {
2023-07-05 21:08:04 +02:00
pub tc_rx: mpsc::Receiver<AcceptedTc>,
pub tc_store: SharedPool,
pub tm_tx: mpsc::Sender<StoreAddr>,
pub tm_store: SharedTmStore,
pub tm_apid: u16,
2023-07-06 00:49:18 +02:00
/// The verification handler is wrapped in a [RefCell] to allow the interior mutability
/// pattern. This makes writing methods which are not mutable a lot easier.
pub verification_handler: RefCell<StdVerifReporterWithSender>,
2023-07-05 21:08:04 +02:00
pub pus_buf: [u8; 2048],
pub pus_size: usize,
2023-07-05 11:25:23 +02:00
}
impl PusServiceBase {
pub fn new(
receiver: mpsc::Receiver<AcceptedTc>,
tc_pool: SharedPool,
tm_tx: mpsc::Sender<StoreAddr>,
tm_store: SharedTmStore,
tm_apid: u16,
verification_handler: StdVerifReporterWithSender,
) -> Self {
Self {
tc_rx: receiver,
tc_store: tc_pool,
tm_apid,
tm_tx,
tm_store,
2023-07-06 00:49:18 +02:00
verification_handler: RefCell::new(verification_handler),
2023-07-05 11:25:23 +02:00
pus_buf: [0; 2048],
pus_size: 0,
}
}
2023-07-05 21:08:04 +02:00
pub fn get_current_timestamp(
&self,
partial_error: &mut Option<PartialPusHandlingError>,
) -> [u8; 7] {
let mut time_stamp: [u8; 7] = [0; 7];
2023-07-05 11:25:23 +02:00
let time_provider =
2023-07-08 13:37:27 +02:00
TimeProvider::from_now_with_u16_days().map_err(PartialPusHandlingError::Time);
2023-07-05 11:25:23 +02:00
if let Ok(time_provider) = time_provider {
2023-07-08 14:57:11 +02:00
// Can't fail, we have a buffer with the exact required size.
2023-07-05 21:08:04 +02:00
time_provider.write_to_bytes(&mut time_stamp).unwrap();
2023-07-05 11:25:23 +02:00
} else {
2023-07-05 21:08:04 +02:00
*partial_error = Some(time_provider.unwrap_err());
2023-07-05 11:25:23 +02:00
}
2023-07-05 21:08:04 +02:00
time_stamp
2023-07-05 11:25:23 +02:00
}
2023-07-06 01:14:01 +02:00
2023-07-05 21:08:04 +02:00
pub fn get_current_timestamp_ignore_error(&self) -> [u8; 7] {
let mut dummy = None;
self.get_current_timestamp(&mut dummy)
2023-07-05 11:58:43 +02:00
}
2023-07-05 11:25:23 +02:00
}
pub trait PusServiceHandler {
fn psb_mut(&mut self) -> &mut PusServiceBase;
fn psb(&self) -> &PusServiceBase;
fn handle_one_tc(
&mut self,
addr: StoreAddr,
token: VerificationToken<TcStateAccepted>,
) -> Result<PusPacketHandlerResult, PusPacketHandlingError>;
2023-07-05 21:08:04 +02:00
fn copy_tc_to_buf(&mut self, addr: StoreAddr) -> Result<(), PusPacketHandlingError> {
// Keep locked section as short as possible.
let psb_mut = self.psb_mut();
let mut tc_pool = psb_mut
.tc_store
.write()
.map_err(|e| PusPacketHandlingError::RwGuardError(format!("{e}")))?;
let tc_guard = tc_pool.read_with_guard(addr);
let tc_raw = tc_guard.read().unwrap();
psb_mut.pus_buf[0..tc_raw.len()].copy_from_slice(tc_raw);
Ok(())
}
2023-07-05 11:25:23 +02:00
fn handle_next_packet(&mut self) -> Result<PusPacketHandlerResult, PusPacketHandlingError> {
return match self.psb().tc_rx.try_recv() {
Ok((addr, token)) => self.handle_one_tc(addr, token),
Err(e) => match e {
mpsc::TryRecvError::Empty => Ok(PusPacketHandlerResult::Empty),
mpsc::TryRecvError::Disconnected => {
Err(PusPacketHandlingError::QueueDisconnected)
}
},
};
}
}
}
2023-07-03 00:42:20 +02:00
pub(crate) fn source_buffer_large_enough(cap: usize, len: usize) -> Result<(), EcssTmtcError> {
if len > cap {
2023-07-08 14:57:11 +02:00
return Err(EcssTmtcError::ByteConversion(
ByteConversionError::ToSliceTooSmall(SizeMissmatch {
found: cap,
expected: len,
}),
));
}
Ok(())
}
#[cfg(test)]
pub(crate) mod tests {
use spacepackets::tm::{GenericPusTmSecondaryHeader, PusTm};
use spacepackets::CcsdsPacket;
#[derive(Debug, Eq, PartialEq, Clone)]
pub(crate) struct CommonTmInfo {
pub subservice: u8,
pub apid: u16,
pub msg_counter: u16,
pub dest_id: u16,
pub time_stamp: [u8; 7],
}
impl CommonTmInfo {
pub fn new_from_tm(tm: &PusTm) -> Self {
let mut time_stamp = [0; 7];
2023-01-21 13:52:21 +01:00
time_stamp.clone_from_slice(&tm.timestamp().unwrap()[0..7]);
Self {
subservice: tm.subservice(),
apid: tm.apid(),
msg_counter: tm.msg_counter(),
dest_id: tm.dest_id(),
time_stamp,
}
}
}
}