472 lines
15 KiB
Rust
472 lines
15 KiB
Rust
use crate::pus::action::send_data_reply;
|
|
/// Device handler implementation for the IMS-100 Imager used on the OPS-SAT mission.
|
|
///
|
|
/// from the [OPSSAT Experimenter Wiki](https://opssat1.esoc.esa.int/projects/experimenter-information/wiki/Camera_Introduction):
|
|
/// OPS-SAT has a BST IMS-100 Imager onboard for image acquisition. These RGGB images are 2048x1944px in size.
|
|
///
|
|
/// There are two ways of taking pictures, with the NMF or by using the camera API directly.
|
|
///
|
|
/// As the NMF method is already explained in the NMF documentation we will focus on triggering the camera API.
|
|
///
|
|
/// The camera is located on the -Z face of OPS-SAT
|
|
///
|
|
/// Mapping between camera and satellite frames:
|
|
/// cam body
|
|
/// +x -z
|
|
/// +y -x
|
|
/// +z +y
|
|
///
|
|
/// If you look onto Flatsat as in your picture coordinate system for camera it is
|
|
///
|
|
/// Z Z pointing inside Flatsat
|
|
/// x---> X
|
|
/// |
|
|
/// |
|
|
/// v Y
|
|
///
|
|
/// see also https://opssat1.esoc.esa.int/dmsf/files/6/view
|
|
use crate::requests::CompositeRequest;
|
|
use derive_new::new;
|
|
use log::{debug, info};
|
|
use ops_sat_rs::TimeStampHelper;
|
|
use satrs::action::{ActionRequest, ActionRequestVariant};
|
|
use satrs::hk::HkRequest;
|
|
use satrs::pus::action::{ActionReplyPus, ActionReplyVariant};
|
|
use satrs::pus::EcssTmtcError;
|
|
use satrs::request::{GenericMessage, MessageMetadata, UniqueApidTargetId};
|
|
use satrs::tmtc::PacketAsVec;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::fmt;
|
|
use std::fmt::Formatter;
|
|
use std::process::{Command, Output};
|
|
use std::sync::mpsc;
|
|
|
|
// const IMS_TESTAPP: &str = "scripts/ims100_testapp";
|
|
const IMS_TESTAPP: &str = "ims100_testapp";
|
|
|
|
const DEFAULT_SINGLE_CAM_PARAMS: CameraPictureParameters = CameraPictureParameters {
|
|
R: 8,
|
|
G: 8,
|
|
B: 8,
|
|
N: 1,
|
|
P: true,
|
|
E: 2,
|
|
W: 1000,
|
|
};
|
|
|
|
const BALANCED_SINGLE_CAM_PARAMS: CameraPictureParameters = CameraPictureParameters {
|
|
R: 13,
|
|
G: 7,
|
|
B: 8,
|
|
N: 1,
|
|
P: true,
|
|
E: 2,
|
|
W: 1000,
|
|
};
|
|
|
|
const DEFAULT_SINGLE_FLATSAT_CAM_PARAMS: CameraPictureParameters = CameraPictureParameters {
|
|
R: 8,
|
|
G: 8,
|
|
B: 8,
|
|
N: 1,
|
|
P: true,
|
|
E: 200,
|
|
W: 1000,
|
|
};
|
|
|
|
const BALANCED_SINGLE_FLATSAT_CAM_PARAMS: CameraPictureParameters = CameraPictureParameters {
|
|
R: 13,
|
|
G: 7,
|
|
B: 8,
|
|
N: 1,
|
|
P: true,
|
|
E: 200,
|
|
W: 1000,
|
|
};
|
|
|
|
// TODO copy as action
|
|
// TODO ls -l via cfdp
|
|
// TODO howto downlink
|
|
|
|
#[derive(Debug)]
|
|
pub enum CameraActionId {
|
|
DefaultSingle = 1,
|
|
BalancedSingle = 2,
|
|
DefaultSingleFlatSat = 3,
|
|
BalancedSingleFlatSat = 4,
|
|
CustomParameters = 5,
|
|
}
|
|
|
|
impl TryFrom<u32> for CameraActionId {
|
|
type Error = ();
|
|
|
|
fn try_from(value: u32) -> Result<Self, Self::Error> {
|
|
match value {
|
|
value if value == CameraActionId::DefaultSingle as u32 => {
|
|
Ok(CameraActionId::DefaultSingle)
|
|
}
|
|
value if value == CameraActionId::BalancedSingle as u32 => {
|
|
Ok(CameraActionId::BalancedSingle)
|
|
}
|
|
value if value == CameraActionId::DefaultSingleFlatSat as u32 => {
|
|
Ok(CameraActionId::DefaultSingleFlatSat)
|
|
}
|
|
value if value == CameraActionId::BalancedSingleFlatSat as u32 => {
|
|
Ok(CameraActionId::BalancedSingleFlatSat)
|
|
}
|
|
value if value == CameraActionId::CustomParameters as u32 => {
|
|
Ok(CameraActionId::CustomParameters)
|
|
}
|
|
_ => Err(()),
|
|
}
|
|
}
|
|
}
|
|
|
|
// TODO what happens if limits are exceded
|
|
#[allow(non_snake_case)]
|
|
#[derive(Debug, Serialize, Deserialize, new)]
|
|
pub struct CameraPictureParameters {
|
|
pub R: u8,
|
|
pub G: u8,
|
|
pub B: u8,
|
|
pub N: u8, // number of images, max: 26
|
|
pub P: bool, // .png flag, true converts raw extracted image from camera to a png
|
|
pub E: u32, // exposure time in ms, max: 1580, default: 2, FlatSat: 200
|
|
pub W: u32, // wait time between pictures in ms, max: 40000
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
#[allow(dead_code)]
|
|
pub enum CameraError {
|
|
TakeImageError,
|
|
NoDataSent,
|
|
VariantNotImplemented,
|
|
DeserializeError,
|
|
ListFileError,
|
|
IoError(std::io::Error),
|
|
EcssTmtcError(EcssTmtcError),
|
|
}
|
|
|
|
impl From<std::io::Error> for CameraError {
|
|
fn from(value: std::io::Error) -> Self {
|
|
Self::IoError(value)
|
|
}
|
|
}
|
|
|
|
impl From<EcssTmtcError> for CameraError {
|
|
fn from(value: EcssTmtcError) -> Self {
|
|
Self::EcssTmtcError(value)
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for CameraError {
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
CameraError::TakeImageError => {
|
|
write!(f, "Error taking image.")
|
|
}
|
|
CameraError::NoDataSent => {
|
|
write!(f, "No data sent.")
|
|
}
|
|
CameraError::VariantNotImplemented => {
|
|
write!(f, "Request variant not implemented.")
|
|
}
|
|
CameraError::DeserializeError => {
|
|
write!(f, "Unable to deserialize parameters.")
|
|
}
|
|
CameraError::ListFileError => {
|
|
write!(f, "Error listing image files.")
|
|
}
|
|
CameraError::IoError(io_error) => {
|
|
write!(f, "{}", io_error)
|
|
}
|
|
CameraError::EcssTmtcError(ecss_tmtc_error) => {
|
|
write!(f, "{}", ecss_tmtc_error)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug)]
|
|
pub struct IMS100BatchHandler {
|
|
id: UniqueApidTargetId,
|
|
// mode_interface: MpscModeLeafInterface,
|
|
composite_request_rx: mpsc::Receiver<GenericMessage<CompositeRequest>>,
|
|
// hk_reply_sender: mpsc::Sender<GenericMessage<HkReply>>,
|
|
tm_tx: mpsc::Sender<PacketAsVec>,
|
|
action_reply_tx: mpsc::Sender<GenericMessage<ActionReplyPus>>,
|
|
stamp_helper: TimeStampHelper,
|
|
}
|
|
|
|
#[allow(non_snake_case)]
|
|
#[allow(dead_code)]
|
|
impl IMS100BatchHandler {
|
|
pub fn new(
|
|
id: UniqueApidTargetId,
|
|
composite_request_rx: mpsc::Receiver<GenericMessage<CompositeRequest>>,
|
|
tm_tx: mpsc::Sender<PacketAsVec>,
|
|
action_reply_tx: mpsc::Sender<GenericMessage<ActionReplyPus>>,
|
|
stamp_helper: TimeStampHelper,
|
|
) -> Self {
|
|
Self {
|
|
id,
|
|
composite_request_rx,
|
|
tm_tx,
|
|
action_reply_tx,
|
|
stamp_helper,
|
|
}
|
|
}
|
|
|
|
pub fn periodic_operation(&mut self) {
|
|
self.stamp_helper.update_from_now();
|
|
// Handle requests.
|
|
self.handle_composite_requests();
|
|
// self.handle_mode_requests();
|
|
}
|
|
|
|
pub fn handle_composite_requests(&mut self) {
|
|
loop {
|
|
match self.composite_request_rx.try_recv() {
|
|
Ok(ref msg) => match &msg.message {
|
|
CompositeRequest::Hk(hk_request) => {
|
|
self.handle_hk_request(&msg.requestor_info, hk_request);
|
|
}
|
|
CompositeRequest::Action(action_request) => {
|
|
if let Err(e) =
|
|
self.handle_action_request(&msg.requestor_info, action_request)
|
|
{
|
|
log::warn!("camera action request IO error: {e}");
|
|
}
|
|
}
|
|
},
|
|
Err(e) => match e {
|
|
mpsc::TryRecvError::Empty => break,
|
|
mpsc::TryRecvError::Disconnected => {
|
|
log::warn!("composite request receiver disconnected");
|
|
break;
|
|
}
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn handle_hk_request(
|
|
&mut self,
|
|
_requestor_info: &MessageMetadata,
|
|
_hk_request: &HkRequest,
|
|
) {
|
|
// TODO add hk to opssat
|
|
}
|
|
|
|
pub fn handle_action_request(
|
|
&mut self,
|
|
requestor_info: &MessageMetadata,
|
|
action_request: &ActionRequest,
|
|
) -> Result<(), CameraError> {
|
|
let param =
|
|
match CameraActionId::try_from(action_request.action_id).expect("Invalid action id") {
|
|
CameraActionId::DefaultSingle => DEFAULT_SINGLE_CAM_PARAMS,
|
|
CameraActionId::BalancedSingle => BALANCED_SINGLE_CAM_PARAMS,
|
|
CameraActionId::DefaultSingleFlatSat => DEFAULT_SINGLE_FLATSAT_CAM_PARAMS,
|
|
CameraActionId::BalancedSingleFlatSat => BALANCED_SINGLE_FLATSAT_CAM_PARAMS,
|
|
CameraActionId::CustomParameters => match &action_request.variant {
|
|
ActionRequestVariant::NoData => return Err(CameraError::NoDataSent),
|
|
ActionRequestVariant::StoreData(_) => {
|
|
// let param = serde_json::from_slice()
|
|
// TODO implement non dynamic version
|
|
return Err(CameraError::VariantNotImplemented);
|
|
}
|
|
ActionRequestVariant::VecData(data) => {
|
|
let param: serde_json::Result<CameraPictureParameters> =
|
|
serde_json::from_slice(data.as_slice());
|
|
match param {
|
|
Ok(param) => param,
|
|
Err(_) => {
|
|
return Err(CameraError::DeserializeError);
|
|
}
|
|
}
|
|
}
|
|
_ => return Err(CameraError::VariantNotImplemented),
|
|
},
|
|
};
|
|
let output = self.take_picture(param)?;
|
|
debug!("Sending action reply!");
|
|
send_data_reply(self.id, output.stdout, &self.stamp_helper, &self.tm_tx)?;
|
|
self.action_reply_tx
|
|
.send(GenericMessage::new(
|
|
*requestor_info,
|
|
ActionReplyPus::new(action_request.action_id, ActionReplyVariant::Completed),
|
|
))
|
|
.unwrap();
|
|
Ok(())
|
|
}
|
|
|
|
pub fn take_picture(&mut self, param: CameraPictureParameters) -> Result<Output, CameraError> {
|
|
info!("Taking image!");
|
|
let mut cmd = Command::new(IMS_TESTAPP);
|
|
cmd.arg("-R")
|
|
.arg(¶m.R.to_string())
|
|
.arg("-G")
|
|
.arg(¶m.G.to_string())
|
|
.arg("-B")
|
|
.arg(¶m.B.to_string())
|
|
.arg("-c")
|
|
.arg("/dev/cam_tty")
|
|
.arg("-m")
|
|
.arg("/dev/cam_sd")
|
|
.arg("-v")
|
|
.arg("0")
|
|
.arg("-n")
|
|
.arg(¶m.N.to_string());
|
|
if param.P {
|
|
cmd.arg("-p");
|
|
}
|
|
cmd.arg("-e")
|
|
.arg(¶m.E.to_string())
|
|
.arg("-w")
|
|
.arg(¶m.W.to_string());
|
|
let output = cmd.output()?;
|
|
|
|
debug!("Imager Output: {}", String::from_utf8_lossy(&output.stdout));
|
|
|
|
Ok(output)
|
|
}
|
|
|
|
pub fn list_current_images(&self) -> Result<Vec<String>, CameraError> {
|
|
let output = Command::new("ls").arg("-l").arg("*.png").output()?;
|
|
|
|
if output.status.success() {
|
|
let output_str = String::from_utf8(output.stdout).unwrap();
|
|
let files: Vec<String> = output_str.lines().map(|s| s.to_string()).collect();
|
|
Ok(files)
|
|
} else {
|
|
Err(CameraError::ListFileError)
|
|
}
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn take_picture_from_str(
|
|
&mut self,
|
|
R: &str,
|
|
G: &str,
|
|
B: &str,
|
|
N: &str,
|
|
P: &str,
|
|
E: &str,
|
|
W: &str,
|
|
) -> Result<(), CameraError> {
|
|
let mut cmd = Command::new("ims100_testapp");
|
|
cmd.arg("-R")
|
|
.arg(R)
|
|
.arg("-G")
|
|
.arg(G)
|
|
.arg("-B")
|
|
.arg(B)
|
|
.arg("-c")
|
|
.arg("/dev/cam_tty")
|
|
.arg("-m")
|
|
.arg("/dev/cam_sd")
|
|
.arg("-v")
|
|
.arg("0")
|
|
.arg("-n")
|
|
.arg(N)
|
|
.arg(P)
|
|
.arg("-e")
|
|
.arg(E)
|
|
.arg("-w")
|
|
.arg(W);
|
|
|
|
let output = cmd.output()?;
|
|
|
|
debug!("{}", String::from_utf8_lossy(&output.stdout));
|
|
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use crate::handlers::camera::{
|
|
CameraActionId, CameraPictureParameters, IMS100BatchHandler,
|
|
DEFAULT_SINGLE_FLATSAT_CAM_PARAMS,
|
|
};
|
|
use crate::requests::CompositeRequest;
|
|
use ops_sat_rs::config::components::CAMERA_HANDLER;
|
|
use ops_sat_rs::TimeStampHelper;
|
|
use satrs::action::{ActionRequest, ActionRequestVariant};
|
|
use satrs::pus::action::ActionReplyPus;
|
|
use satrs::request::{GenericMessage, MessageMetadata};
|
|
use satrs::tmtc::PacketAsVec;
|
|
use std::sync::mpsc;
|
|
use std::sync::mpsc::{Receiver, Sender};
|
|
|
|
fn create_handler() -> (
|
|
IMS100BatchHandler,
|
|
Sender<GenericMessage<CompositeRequest>>,
|
|
Receiver<PacketAsVec>,
|
|
Receiver<GenericMessage<ActionReplyPus>>,
|
|
) {
|
|
let (composite_request_tx, composite_request_rx) = mpsc::channel();
|
|
let (tm_tx, tm_rx) = mpsc::channel();
|
|
let (action_reply_tx, action_reply_rx) = mpsc::channel();
|
|
let time_helper = TimeStampHelper::default();
|
|
let cam_handler: IMS100BatchHandler = IMS100BatchHandler::new(
|
|
CAMERA_HANDLER,
|
|
composite_request_rx,
|
|
tm_tx,
|
|
action_reply_tx,
|
|
time_helper,
|
|
);
|
|
(cam_handler, composite_request_tx, tm_rx, action_reply_rx)
|
|
}
|
|
|
|
#[test]
|
|
fn command_line_execution() {
|
|
let (mut cam_handler, req_tx, tm_rx, action_reply_rx) = create_handler();
|
|
cam_handler
|
|
.take_picture(DEFAULT_SINGLE_FLATSAT_CAM_PARAMS)
|
|
.unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn serialize_and_deserialize_command() {
|
|
let data = serde_json::to_string(&DEFAULT_SINGLE_FLATSAT_CAM_PARAMS).unwrap();
|
|
println!("{}", data);
|
|
let param: CameraPictureParameters = serde_json::from_str(&data).unwrap();
|
|
println!("{:?}", param);
|
|
}
|
|
|
|
#[test]
|
|
fn test_action_req() {
|
|
let (mut cam_handler, req_tx, tm_rx, action_reply_rx) = create_handler();
|
|
|
|
let data = serde_json::to_string(&DEFAULT_SINGLE_FLATSAT_CAM_PARAMS).unwrap();
|
|
let req = ActionRequest::new(
|
|
CameraActionId::CustomParameters as u32,
|
|
ActionRequestVariant::VecData(data.as_bytes().to_vec()),
|
|
);
|
|
|
|
cam_handler
|
|
.handle_action_request(&MessageMetadata::new(1, 1), &req)
|
|
.unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn test_action_req_channel() {
|
|
let (mut cam_handler, req_tx, tm_rx, action_reply_rx) = create_handler();
|
|
|
|
let data = serde_json::to_string(&DEFAULT_SINGLE_FLATSAT_CAM_PARAMS).unwrap();
|
|
let req = ActionRequest::new(
|
|
CameraActionId::CustomParameters as u32,
|
|
ActionRequestVariant::VecData(data.as_bytes().to_vec()),
|
|
);
|
|
let req = CompositeRequest::Action(req);
|
|
req_tx
|
|
.send(GenericMessage::new(MessageMetadata::new(1, 1), req))
|
|
.unwrap();
|
|
|
|
cam_handler.periodic_operation();
|
|
}
|
|
}
|