use std::sync::Arc;
use std::time::Duration;
use crate::error::{GenicamError, GenicamResult};
use crate::gige::stream::{Frame, FrameChannel, StreamChannel, StreamConfig};
use super::GenICamera;
#[derive(Debug)]
pub struct SnapshotSession<'a> {
cam: &'a mut GenICamera,
stream: StreamChannel,
frames: FrameChannel,
auto_stops: bool,
restore_mode: Option<String>,
}
impl<'a> SnapshotSession<'a> {
pub(crate) fn open(cam: &'a mut GenICamera, mut cfg: StreamConfig) -> GenicamResult<Self> {
let mut restore_mode = None;
let auto_stops = match cam.get_enum("AcquisitionMode") {
Ok(mode) if mode == "SingleFrame" => true,
Ok(mode) => match cam.set_enum("AcquisitionMode", "SingleFrame") {
Ok(()) => {
restore_mode = Some(mode);
true
}
Err(e) => {
tracing::debug!("SingleFrame mode unavailable, stopping per snap: {e}");
false
}
},
Err(e) => {
tracing::debug!("AcquisitionMode unavailable, stopping per snap: {e}");
false
}
};
let stream = cam
.fill_payload_size(&mut cfg)
.and_then(|()| Ok(cam.transport().open_stream(cfg)?));
let stream = match stream {
Ok(stream) => stream,
Err(e) => {
if let Some(mode) = restore_mode {
let _ = cam.set_enum("AcquisitionMode", &mode);
}
return Err(e);
}
};
if let Err(e) = cam.set_integer("TLParamsLocked", 1) {
tracing::debug!("TLParamsLocked not set: {e}");
}
let frames = stream.subscribe(4);
Ok(Self {
cam,
stream,
frames,
auto_stops,
restore_mode,
})
}
pub fn snap(&mut self, timeout: Duration) -> GenicamResult<Arc<Frame>> {
self.frames.clear();
self.cam.execute("AcquisitionStart")?;
let frame = self.frames.wait_for(timeout);
if (!self.auto_stops || frame.is_none())
&& let Err(e) = self.cam.execute("AcquisitionStop")
{
tracing::warn!("AcquisitionStop after snap failed: {e}");
}
frame.ok_or(GenicamError::FrameTimeout)
}
pub fn stream(&self) -> &StreamChannel {
&self.stream
}
pub fn features(&mut self) -> super::Features<'_> {
super::Features(self.cam)
}
}
impl Drop for SnapshotSession<'_> {
fn drop(&mut self) {
if let Err(e) = self.cam.set_integer("TLParamsLocked", 0) {
tracing::debug!("TLParamsLocked not cleared: {e}");
}
if let Some(mode) = self.restore_mode.take()
&& let Err(e) = self.cam.set_enum("AcquisitionMode", &mode)
{
tracing::debug!("AcquisitionMode not restored: {e}");
}
}
}