first implementation of apid with target id, currently main broken

This commit is contained in:
lkoester 2023-08-15 08:49:54 +02:00
parent 698c2edb93
commit 075dc38434
8 changed files with 163 additions and 79 deletions

View File

@ -10,6 +10,7 @@ use downcast_rs::{impl_downcast, Downcast};
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use spacepackets::{ByteConversionError, SizeMissmatch, SpHeader}; use spacepackets::{ByteConversionError, SizeMissmatch, SpHeader};
use spacepackets::ecss::tc::PusTc;
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
pub mod ccsds_distrib; pub mod ccsds_distrib;
@ -24,40 +25,6 @@ pub use pus_distrib::{PusDistributor, PusServiceProvider};
pub type TargetId = u32; 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(SizeMissmatch {
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(SizeMissmatch {
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 /// Generic trait for object which can receive any telecommands in form of a raw bytestream, with
/// no assumptions about the received protocol. /// no assumptions about the received protocol.
/// ///

View File

@ -15,9 +15,16 @@ zerocopy = "0.6"
csv = "1" csv = "1"
num_enum = "0.6" num_enum = "0.6"
thiserror = "1" thiserror = "1"
embedded-can = "0.4"
#socketcan = "2.0"
derive-new = "0.5"
num-traits = "0.2"
num-derive = "0.3"
[dependencies.satrs-core] [dependencies.satrs-core]
path = "../satrs-core" path = "../satrs-core"
[dependencies.satrs-mib] [dependencies.satrs-mib]
path = "../satrs-mib" path = "../satrs-mib"

View File

@ -1,11 +1,102 @@
use std::fmt;
use num_enum::{IntoPrimitive, TryFromPrimitive}; use num_enum::{IntoPrimitive, TryFromPrimitive};
use satrs_core::events::{EventU32TypedSev, SeverityInfo}; use satrs_core::events::{EventU32TypedSev, SeverityInfo};
use satrs_core::objects::ObjectId; use satrs_core::objects::ObjectId;
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use delegate::delegate;
use derive_new::new;
use thiserror::Error;
use satrs_core::spacepackets::{ByteConversionError, CcsdsPacket, SizeMissmatch};
use satrs_core::spacepackets::ecss::PusPacket;
use satrs_core::spacepackets::ecss::tc::{GenericPusTcSecondaryHeader, IsPusTelecommand, PusTc};
use satrs_core::tmtc::TargetId;
use satrs_mib::res_code::{ResultU16, ResultU16Info}; use satrs_mib::res_code::{ResultU16, ResultU16Info};
use satrs_mib::resultcode; use satrs_mib::resultcode;
//pub mod can;
//mod can_ids;
mod logger;
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(SizeMissmatch {
found: tc.user_data().len(),
expected: 8,
}).into());
}
let target_id = u32::from_be_bytes(tc.user_data()[0..4].try_into().unwrap());
Ok(Self {
apid: tc.apid(),
target: u32::from_be_bytes(tc.user_data()[0..4].try_into().unwrap()),
})
}
}
// #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, new)]
// #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
// pub struct TargetIdWithUniqueId {
// target_id: TargetIdWithApid,
// unique_id: u32,
// }
//
// impl TargetIdWithUniqueId {
// delegate! {
// to self.target_id {
// pub fn apid(&self) -> Apid;
// pub fn target_id(&self) -> TargetId;
// }
// }
// pub fn unique_id(&self) -> u32 {
// self.unique_id
// }
//
// pub fn write_target_id_and_unique_id_as_pus_header(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
// if buf.len() < 8 {
// return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
// found: buf.len(),
// expected: 8,
// }));
// }
// buf[0..4].copy_from_slice(&self.target_id.target_id().to_be_bytes());
// buf[4..8].copy_from_slice(&self.unique_id.to_be_bytes());
// Ok(8)
// }
// }
//
pub const PUS_APID: u16 = 0x02; pub const PUS_APID: u16 = 0x02;
#[derive(Copy, Clone, PartialEq, Eq, Debug, TryFromPrimitive, IntoPrimitive)] #[derive(Copy, Clone, PartialEq, Eq, Debug, TryFromPrimitive, IntoPrimitive)]
@ -20,6 +111,8 @@ pub enum RequestTargetId {
AcsSubsystem = 1, AcsSubsystem = 1,
} }
pub const AOCS_APID: u16 = 1;
pub const ACS_OBJECT_ID: ObjectId = ObjectId { pub const ACS_OBJECT_ID: ObjectId = ObjectId {
id: RequestTargetId::AcsSubsystem as u32, id: RequestTargetId::AcsSubsystem as u32,
name: "ACS_SUBSYSTEM", name: "ACS_SUBSYSTEM",

View File

@ -0,0 +1,22 @@
#![allow(unused_imports)]
use chrono;
use log::{debug, error, info, trace, warn};
pub fn setup_logger() -> Result<(), fern::InitError> {
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
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

@ -4,6 +4,8 @@ mod logging;
mod pus; mod pus;
mod requests; mod requests;
mod tmtc; mod tmtc;
//mod can;
//mod can_ids;
use log::{info, warn}; use log::{info, warn};
@ -43,11 +45,9 @@ use satrs_core::spacepackets::{
SpHeader, SpHeader,
}; };
use satrs_core::tmtc::tm_helper::SharedTmStore; use satrs_core::tmtc::tm_helper::SharedTmStore;
use satrs_core::tmtc::{AddressableId, TargetId}; use satrs_core::tmtc::{TargetId};
use satrs_core::ChannelId; use satrs_core::ChannelId;
use satrs_example::{ use satrs_example::{RequestTargetId, TcReceiverId, TmSenderId, OBSW_SERVER_ADDR, PUS_APID, SERVER_PORT, TargetIdWithApid};
RequestTargetId, TcReceiverId, TmSenderId, OBSW_SERVER_ADDR, PUS_APID, SERVER_PORT,
};
use std::collections::HashMap; use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr}; use std::net::{IpAddr, SocketAddr};
use std::sync::mpsc::{channel, TryRecvError}; use std::sync::mpsc::{channel, TryRecvError};
@ -124,7 +124,8 @@ fn main() {
// Some request are targetable. This map is used to retrieve sender handles based on a target ID. // Some request are targetable. This map is used to retrieve sender handles based on a target ID.
let mut request_map = HashMap::new(); let mut request_map = HashMap::new();
let (acs_thread_tx, acs_thread_rx) = channel::<RequestWithToken>(); 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 { let tc_source_wrapper = PusTcSource {
tc_store: tc_store.clone(), tc_store: tc_store.clone(),
@ -393,8 +394,8 @@ fn main() {
Request::Hk(hk_req) => match hk_req { Request::Hk(hk_req) => match hk_req {
HkRequest::OneShot(unique_id) => { HkRequest::OneShot(unique_id) => {
let target = request.targeted_request.target_id; let target = request.targeted_request.target_id;
assert_eq!(target, RequestTargetId::AcsSubsystem as u32); assert_eq!(target.target_id(), RequestTargetId::AcsSubsystem as u32);
if request.targeted_request.target_id if request.targeted_request.target_id.target
== AcsHkIds::TestMgmSet as u32 == AcsHkIds::TestMgmSet as u32
{ {
let mut sp_header = SpHeader::tm( let mut sp_header = SpHeader::tm(
@ -410,11 +411,8 @@ fn main() {
&timestamp, &timestamp,
); );
let mut buf: [u8; 8] = [0; 8]; let mut buf: [u8; 8] = [0; 8];
let addressable_id = AddressableId {
target_id: target, target.target.write_to_be_bytes(&mut buf).unwrap();
unique_id,
};
addressable_id.write_to_be_bytes(&mut buf).unwrap();
let pus_tm = PusTmCreator::new( let pus_tm = PusTmCreator::new(
&mut sp_header, &mut sp_header,
sec_header, sec_header,

View File

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

View File

@ -1,6 +1,6 @@
use crate::requests::{Request, RequestWithToken}; use crate::requests::{Request, RequestWithToken};
use log::{error, warn}; use log::{error, warn};
use satrs_core::hk::{CollectionIntervalFactor, HkRequest}; use satrs_core::hk::{CollectionIntervalFactor, HkRequest, UniqueId};
use satrs_core::pool::{SharedPool, StoreAddr}; use satrs_core::pool::{SharedPool, StoreAddr};
use satrs_core::pus::verification::{ use satrs_core::pus::verification::{
FailParams, StdVerifReporterWithSender, TcStateAccepted, VerificationToken, FailParams, StdVerifReporterWithSender, TcStateAccepted, VerificationToken,
@ -11,14 +11,14 @@ use satrs_core::pus::{
}; };
use satrs_core::spacepackets::ecss::tc::PusTcReader; use satrs_core::spacepackets::ecss::tc::PusTcReader;
use satrs_core::spacepackets::ecss::{hk, PusPacket}; use satrs_core::spacepackets::ecss::{hk, PusPacket};
use satrs_core::tmtc::{AddressableId, TargetId}; use satrs_core::tmtc::TargetId;
use satrs_example::{hk_err, tmtc_err}; use satrs_example::{hk_err, TargetIdWithApid, tmtc_err};
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::mpsc::Sender; use std::sync::mpsc::Sender;
pub struct PusService3HkHandler { pub struct PusService3HkHandler {
psb: PusServiceBase, psb: PusServiceBase,
request_handlers: HashMap<TargetId, Sender<RequestWithToken>>, request_handlers: HashMap<TargetIdWithApid, Sender<RequestWithToken>>,
} }
impl PusService3HkHandler { impl PusService3HkHandler {
@ -28,7 +28,7 @@ impl PusService3HkHandler {
tm_sender: Box<dyn EcssTmSender>, tm_sender: Box<dyn EcssTmSender>,
tm_apid: u16, tm_apid: u16,
verification_handler: StdVerifReporterWithSender, verification_handler: StdVerifReporterWithSender,
request_handlers: HashMap<TargetId, Sender<RequestWithToken>>, request_handlers: HashMap<TargetIdWithApid, Sender<RequestWithToken>>,
) -> Self { ) -> Self {
Self { Self {
psb: PusServiceBase::new( psb: PusServiceBase::new(
@ -90,10 +90,11 @@ impl PusServiceHandler for PusService3HkHandler {
"Expected at least 8 bytes of app data".into(), "Expected at least 8 bytes of app data".into(),
)); ));
} }
let addressable_id = AddressableId::from_raw_be(user_data).unwrap(); 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 if !self
.request_handlers .request_handlers
.contains_key(&addressable_id.target_id) .contains_key(&target_id)
{ {
self.psb self.psb
.verification_handler .verification_handler
@ -103,15 +104,14 @@ impl PusServiceHandler for PusService3HkHandler {
FailParams::new(Some(&time_stamp), &hk_err::UNKNOWN_TARGET_ID, None), FailParams::new(Some(&time_stamp), &hk_err::UNKNOWN_TARGET_ID, None),
) )
.expect("Sending start failure TM failed"); .expect("Sending start failure TM failed");
let tgt_id = addressable_id.target_id;
return Err(PusPacketHandlingError::NotEnoughAppData(format!( return Err(PusPacketHandlingError::NotEnoughAppData(format!(
"Unknown target ID {tgt_id}" "Unknown target ID {target_id}"
))); )));
} }
let send_request = |target: TargetId, request: HkRequest| { let send_request = |target: TargetIdWithApid, request: HkRequest| {
let sender = self let sender = self
.request_handlers .request_handlers
.get(&addressable_id.target_id) .get(&target)
.unwrap(); .unwrap();
sender sender
.send(RequestWithToken::new(target, Request::Hk(request), token)) .send(RequestWithToken::new(target, Request::Hk(request), token))
@ -119,18 +119,18 @@ impl PusServiceHandler for PusService3HkHandler {
}; };
if subservice == hk::Subservice::TcEnableHkGeneration as u8 { if subservice == hk::Subservice::TcEnableHkGeneration as u8 {
send_request( send_request(
addressable_id.target_id, target_id,
HkRequest::Enable(addressable_id.unique_id), HkRequest::Enable(unique_id),
); );
} else if subservice == hk::Subservice::TcDisableHkGeneration as u8 { } else if subservice == hk::Subservice::TcDisableHkGeneration as u8 {
send_request( send_request(
addressable_id.target_id, target_id,
HkRequest::Disable(addressable_id.unique_id), HkRequest::Disable(unique_id),
); );
} else if subservice == hk::Subservice::TcGenerateOneShotHk as u8 { } else if subservice == hk::Subservice::TcGenerateOneShotHk as u8 {
send_request( send_request(
addressable_id.target_id, target_id,
HkRequest::OneShot(addressable_id.unique_id), HkRequest::OneShot(unique_id),
); );
} else if subservice == hk::Subservice::TcModifyHkCollectionInterval as u8 { } else if subservice == hk::Subservice::TcModifyHkCollectionInterval as u8 {
if user_data.len() < 12 { if user_data.len() < 12 {
@ -151,9 +151,9 @@ impl PusServiceHandler for PusService3HkHandler {
)); ));
} }
send_request( send_request(
addressable_id.target_id, target_id,
HkRequest::ModifyCollectionInterval( HkRequest::ModifyCollectionInterval(
addressable_id.unique_id, unique_id,
CollectionIntervalFactor::from_be_bytes(user_data[8..12].try_into().unwrap()), CollectionIntervalFactor::from_be_bytes(user_data[8..12].try_into().unwrap()),
), ),
); );

View File

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