Merge pull request 'TargetIdWithApid' (#63) from TargetIdWithApid into main
All checks were successful
Rust/sat-rs/pipeline/head This commit looks good

Reviewed-on: #63
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
This commit is contained in:
Robin Müller 2024-01-31 11:06:33 +01:00
commit a09af65396
10 changed files with 138 additions and 97 deletions

View File

@ -7,9 +7,7 @@
//! routing without the overhead and complication of using message queues. However, it also requires
#[cfg(feature = "alloc")]
use downcast_rs::{impl_downcast, Downcast};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use spacepackets::{ByteConversionError, SpHeader};
use spacepackets::SpHeader;
#[cfg(feature = "alloc")]
pub mod ccsds_distrib;
@ -24,40 +22,6 @@ pub use pus_distrib::{PusDistributor, PusServiceProvider};
pub type TargetId = u32;
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct AddressableId {
pub target_id: TargetId,
pub unique_id: u32,
}
impl AddressableId {
pub fn from_raw_be(buf: &[u8]) -> Result<Self, ByteConversionError> {
if buf.len() < 8 {
return Err(ByteConversionError::FromSliceTooSmall {
found: buf.len(),
expected: 8,
});
}
Ok(Self {
target_id: u32::from_be_bytes(buf[0..4].try_into().unwrap()),
unique_id: u32::from_be_bytes(buf[4..8].try_into().unwrap()),
})
}
pub fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
if buf.len() < 8 {
return Err(ByteConversionError::ToSliceTooSmall {
found: buf.len(),
expected: 8,
});
}
buf[0..4].copy_from_slice(&self.target_id.to_be_bytes());
buf[4..8].copy_from_slice(&self.unique_id.to_be_bytes());
Ok(8)
}
}
/// Generic trait for object which can receive any telecommands in form of a raw bytestream, with
/// no assumptions about the received protocol.
///

1
satrs-example/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/output.log

View File

@ -17,6 +17,7 @@ zerocopy = "0.6"
csv = "1"
num_enum = "0.7"
thiserror = "1"
derive-new = "0.5"
[dependencies.satrs-core]
# version = "0.1.0-alpha.1"

View File

@ -1,4 +1,37 @@
use derive_new::new;
use satrs_core::spacepackets::ByteConversionError;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum AcsHkIds {
TestMgmSet = 1,
}
#[derive(Debug, new, Copy, Clone)]
pub struct HkUniqueId {
target_id: u32,
set_id: u32,
}
impl HkUniqueId {
#[allow(dead_code)]
pub fn target_id(&self) -> u32 {
self.target_id
}
#[allow(dead_code)]
pub fn set_id(&self) -> u32 {
self.set_id
}
pub fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
if buf.len() < 8 {
return Err(ByteConversionError::ToSliceTooSmall {
found: buf.len(),
expected: 8,
});
}
buf[0..4].copy_from_slice(&self.target_id.to_be_bytes());
buf[4..8].copy_from_slice(&self.set_id.to_be_bytes());
Ok(8)
}
}

View File

@ -1,11 +1,68 @@
use derive_new::new;
use num_enum::{IntoPrimitive, TryFromPrimitive};
use satrs_core::events::{EventU32TypedSev, SeverityInfo};
use satrs_core::objects::ObjectId;
use satrs_core::spacepackets::ecss::tc::IsPusTelecommand;
use satrs_core::spacepackets::ecss::PusPacket;
use satrs_core::spacepackets::{ByteConversionError, CcsdsPacket};
use satrs_core::tmtc::TargetId;
use std::fmt;
use std::net::Ipv4Addr;
use thiserror::Error;
use satrs_mib::res_code::{ResultU16, ResultU16Info};
use satrs_mib::resultcode;
pub type Apid = u16;
#[derive(Debug, Error)]
pub enum TargetIdCreationError {
#[error("byte conversion")]
ByteConversion(#[from] ByteConversionError),
#[error("not enough app data to generate target ID")]
NotEnoughAppData(usize),
}
// TODO: can these stay pub?
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, new)]
pub struct TargetIdWithApid {
pub apid: Apid,
pub target: TargetId,
}
impl fmt::Display for TargetIdWithApid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}, {}", self.apid, self.target)
}
}
impl TargetIdWithApid {
pub fn apid(&self) -> Apid {
self.apid
}
pub fn target_id(&self) -> TargetId {
self.target
}
}
impl TargetIdWithApid {
pub fn from_tc(
tc: &(impl CcsdsPacket + PusPacket + IsPusTelecommand),
) -> Result<Self, TargetIdCreationError> {
if tc.user_data().len() < 4 {
return Err(ByteConversionError::FromSliceTooSmall {
found: tc.user_data().len(),
expected: 8,
}
.into());
}
Ok(Self {
apid: tc.apid(),
target: u32::from_be_bytes(tc.user_data()[0..4].try_into().unwrap()),
})
}
}
pub const PUS_APID: u16 = 0x02;
#[derive(Copy, Clone, PartialEq, Eq, Debug, TryFromPrimitive, IntoPrimitive)]
@ -20,6 +77,8 @@ pub enum RequestTargetId {
AcsSubsystem = 1,
}
pub const AOCS_APID: u16 = 1;
pub const ACS_OBJECT_ID: ObjectId = ObjectId {
id: RequestTargetId::AcsSubsystem as u32,
name: "ACS_SUBSYSTEM",

View File

@ -4,13 +4,14 @@ pub fn setup_logger() -> Result<(), fern::InitError> {
out.finish(format_args!(
"{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.target(), //(std::thread::current().name().expect("unnamed_thread"),
std::thread::current().name().expect("unnamed_thread"),
record.level(),
message
))
})
.level(log::LevelFilter::Debug)
.chain(std::io::stdout())
.chain(fern::log_file("output.log")?)
.apply()?;
Ok(())
}

View File

@ -1,6 +1,6 @@
mod ccsds;
mod hk;
mod logging;
mod logger;
mod pus;
mod requests;
mod tcp;
@ -12,8 +12,8 @@ use satrs_core::hal::std::tcp_server::ServerConfig;
use satrs_core::hal::std::udp_server::UdpTcServer;
use crate::ccsds::CcsdsReceiver;
use crate::hk::AcsHkIds;
use crate::logging::setup_logger;
use crate::hk::{AcsHkIds, HkUniqueId};
use crate::logger::setup_logger;
use crate::pus::action::{Pus8Wrapper, PusService8ActionHandler};
use crate::pus::event::Pus5Wrapper;
use crate::pus::hk::{Pus3Wrapper, PusService3HkHandler};
@ -50,10 +50,11 @@ use satrs_core::spacepackets::{
SpHeader,
};
use satrs_core::tmtc::tm_helper::SharedTmStore;
use satrs_core::tmtc::{AddressableId, CcsdsDistributor, TargetId};
use satrs_core::tmtc::{CcsdsDistributor, TargetId};
use satrs_core::ChannelId;
use satrs_example::{
RequestTargetId, TcReceiverId, TmSenderId, OBSW_SERVER_ADDR, PUS_APID, SERVER_PORT,
RequestTargetId, TargetIdWithApid, TcReceiverId, TmSenderId, OBSW_SERVER_ADDR, PUS_APID,
SERVER_PORT,
};
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
@ -131,7 +132,8 @@ fn main() {
// Some request are targetable. This map is used to retrieve sender handles based on a target ID.
let mut request_map = HashMap::new();
let (acs_thread_tx, acs_thread_rx) = channel::<RequestWithToken>();
request_map.insert(RequestTargetId::AcsSubsystem as TargetId, acs_thread_tx);
let target_apid = TargetIdWithApid::new(PUS_APID, RequestTargetId::AcsSubsystem as TargetId);
request_map.insert(target_apid, acs_thread_tx);
let tc_source_wrapper = PusTcSource {
tc_store: tc_store.clone(),
@ -440,9 +442,13 @@ fn main() {
match request.targeted_request.request {
Request::Hk(hk_req) => match hk_req {
HkRequest::OneShot(unique_id) => {
// TODO: We should check whether the unique ID is even valid.
let target = request.targeted_request.target_id;
assert_eq!(target, RequestTargetId::AcsSubsystem as u32);
if request.targeted_request.target_id
assert_eq!(
target.target_id(),
RequestTargetId::AcsSubsystem as u32
);
if request.targeted_request.target_id.target
== AcsHkIds::TestMgmSet as u32
{
let mut sp_header = SpHeader::tm(
@ -458,11 +464,8 @@ fn main() {
&timestamp,
);
let mut buf: [u8; 8] = [0; 8];
let addressable_id = AddressableId {
target_id: target,
unique_id,
};
addressable_id.write_to_be_bytes(&mut buf).unwrap();
let hk_id = HkUniqueId::new(target.target_id(), unique_id);
hk_id.write_to_be_bytes(&mut buf).unwrap();
let pus_tm = PusTmCreator::new(
&mut sp_header,
sec_header,

View File

@ -10,14 +10,13 @@ use satrs_core::pus::{
};
use satrs_core::spacepackets::ecss::tc::PusTcReader;
use satrs_core::spacepackets::ecss::PusPacket;
use satrs_core::tmtc::TargetId;
use satrs_example::tmtc_err;
use satrs_example::{tmtc_err, TargetIdWithApid};
use std::collections::HashMap;
use std::sync::mpsc::Sender;
pub struct PusService8ActionHandler {
psb: PusServiceBase,
request_handlers: HashMap<TargetId, Sender<RequestWithToken>>,
request_handlers: HashMap<TargetIdWithApid, Sender<RequestWithToken>>,
}
impl PusService8ActionHandler {
@ -27,7 +26,7 @@ impl PusService8ActionHandler {
tm_sender: Box<dyn EcssTmSender>,
tm_apid: u16,
verification_handler: StdVerifReporterWithSender,
request_handlers: HashMap<TargetId, Sender<RequestWithToken>>,
request_handlers: HashMap<TargetIdWithApid, Sender<RequestWithToken>>,
) -> Self {
Self {
psb: PusServiceBase::new(
@ -63,7 +62,8 @@ impl PusService8ActionHandler {
"Expected at least 4 bytes".into(),
));
}
let target_id = u32::from_be_bytes(user_data[0..4].try_into().unwrap());
//let target_id = u32::from_be_bytes(user_data[0..4].try_into().unwrap());
let target_id = TargetIdWithApid::from_tc(tc).unwrap();
let action_id = u32::from_be_bytes(user_data[4..8].try_into().unwrap());
if let Some(sender) = self.request_handlers.get(&target_id) {
sender
@ -78,7 +78,7 @@ impl PusService8ActionHandler {
.expect("Forwarding action request failed");
} else {
let mut fail_data: [u8; 4] = [0; 4];
fail_data.copy_from_slice(&target_id.to_be_bytes());
fail_data.copy_from_slice(&target_id.target.to_be_bytes());
self.psb()
.verification_handler
.borrow_mut()

View File

@ -11,14 +11,13 @@ use satrs_core::pus::{
};
use satrs_core::spacepackets::ecss::tc::PusTcReader;
use satrs_core::spacepackets::ecss::{hk, PusPacket};
use satrs_core::tmtc::{AddressableId, TargetId};
use satrs_example::{hk_err, tmtc_err};
use satrs_example::{hk_err, tmtc_err, TargetIdWithApid};
use std::collections::HashMap;
use std::sync::mpsc::Sender;
pub struct PusService3HkHandler {
psb: PusServiceBase,
request_handlers: HashMap<TargetId, Sender<RequestWithToken>>,
request_handlers: HashMap<TargetIdWithApid, Sender<RequestWithToken>>,
}
impl PusService3HkHandler {
@ -28,7 +27,7 @@ impl PusService3HkHandler {
tm_sender: Box<dyn EcssTmSender>,
tm_apid: u16,
verification_handler: StdVerifReporterWithSender,
request_handlers: HashMap<TargetId, Sender<RequestWithToken>>,
request_handlers: HashMap<TargetIdWithApid, Sender<RequestWithToken>>,
) -> Self {
Self {
psb: PusServiceBase::new(
@ -90,11 +89,9 @@ impl PusServiceHandler for PusService3HkHandler {
"Expected at least 8 bytes of app data".into(),
));
}
let addressable_id = AddressableId::from_raw_be(user_data).unwrap();
if !self
.request_handlers
.contains_key(&addressable_id.target_id)
{
let target_id = TargetIdWithApid::from_tc(&tc).expect("invalid tc format");
let unique_id = u32::from_be_bytes(tc.user_data()[0..4].try_into().unwrap());
if !self.request_handlers.contains_key(&target_id) {
self.psb
.verification_handler
.borrow_mut()
@ -103,35 +100,22 @@ impl PusServiceHandler for PusService3HkHandler {
FailParams::new(Some(&time_stamp), &hk_err::UNKNOWN_TARGET_ID, None),
)
.expect("Sending start failure TM failed");
let tgt_id = addressable_id.target_id;
return Err(PusPacketHandlingError::NotEnoughAppData(format!(
"Unknown target ID {tgt_id}"
"Unknown target ID {target_id}"
)));
}
let send_request = |target: TargetId, request: HkRequest| {
let sender = self
.request_handlers
.get(&addressable_id.target_id)
.unwrap();
let send_request = |target: TargetIdWithApid, request: HkRequest| {
let sender = self.request_handlers.get(&target).unwrap();
sender
.send(RequestWithToken::new(target, Request::Hk(request), token))
.unwrap_or_else(|_| panic!("Sending HK request {request:?} failed"));
};
if subservice == hk::Subservice::TcEnableHkGeneration as u8 {
send_request(
addressable_id.target_id,
HkRequest::Enable(addressable_id.unique_id),
);
send_request(target_id, HkRequest::Enable(unique_id));
} else if subservice == hk::Subservice::TcDisableHkGeneration as u8 {
send_request(
addressable_id.target_id,
HkRequest::Disable(addressable_id.unique_id),
);
send_request(target_id, HkRequest::Disable(unique_id));
} else if subservice == hk::Subservice::TcGenerateOneShotHk as u8 {
send_request(
addressable_id.target_id,
HkRequest::OneShot(addressable_id.unique_id),
);
send_request(target_id, HkRequest::OneShot(unique_id));
} else if subservice == hk::Subservice::TcModifyHkCollectionInterval as u8 {
if user_data.len() < 12 {
self.psb
@ -151,9 +135,9 @@ impl PusServiceHandler for PusService3HkHandler {
));
}
send_request(
addressable_id.target_id,
target_id,
HkRequest::ModifyCollectionInterval(
addressable_id.unique_id,
unique_id,
CollectionIntervalFactor::from_be_bytes(user_data[8..12].try_into().unwrap()),
),
);

View File

@ -1,7 +1,8 @@
use derive_new::new;
use satrs_core::hk::HkRequest;
use satrs_core::mode::ModeRequest;
use satrs_core::pus::verification::{TcStateAccepted, VerificationToken};
use satrs_core::tmtc::TargetId;
use satrs_example::TargetIdWithApid;
#[allow(dead_code)]
#[derive(Clone, Eq, PartialEq, Debug)]
@ -19,18 +20,12 @@ pub enum Request {
Action(ActionRequest),
}
#[derive(Clone, Eq, PartialEq, Debug)]
#[derive(Clone, Eq, PartialEq, Debug, new)]
pub struct TargetedRequest {
pub(crate) target_id: TargetId,
pub(crate) target_id: TargetIdWithApid,
pub(crate) request: Request,
}
impl TargetedRequest {
pub fn new(target_id: TargetId, request: Request) -> Self {
Self { target_id, request }
}
}
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct RequestWithToken {
pub(crate) targeted_request: TargetedRequest,
@ -39,7 +34,7 @@ pub struct RequestWithToken {
impl RequestWithToken {
pub fn new(
target_id: u32,
target_id: TargetIdWithApid,
request: Request,
token: VerificationToken<TcStateAccepted>,
) -> Self {