use std::path::PathBuf;
use std::time::Duration;
use printobserver_printer_api::{JobSnapshot, PrinterSnapshot, PrinterState};
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId};
use crate::error::CoreError;
use crate::inbox::Arrival;
use crate::kinds::{CameraDegradedPayload, CameraLookPayload, FrameCause, PortFailureSite};
use crate::supervisor::Supervisor;
use printobserver_vision_api::{FetchedImage, FrameFault};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct Look {
pub event: EventRecord,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub arrived: Vec<EventRecord>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub frame: Option<ImageRef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub image_path: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub printer: Option<PrinterSnapshot>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub job: Option<JobSnapshot>,
pub detector_paused: bool,
}
impl Sample for Look {
fn sample_full() -> Self {
Self {
event: EventRecord::sample_full(),
arrived: vec![EventRecord::sample_full()],
frame: Some(ImageRef::sample_full()),
image_path: Some(PathBuf::from("/var/lib/printobserver/images/look.jpg")),
printer: Some(PrinterSnapshot::sample_full()),
job: Some(JobSnapshot::sample_full()),
detector_paused: true,
}
}
fn sample_minimal() -> Self {
Self {
event: EventRecord::sample_minimal(),
arrived: Vec::new(),
frame: None,
image_path: None,
printer: None,
job: None,
detector_paused: false,
}
}
}
impl Supervisor {
#[must_use]
pub fn await_arrivals(&self, print_id: PrintId, wait: Duration) -> Vec<Arrival> {
self.inboxes().wait_and_take(print_id, wait)
}
pub async fn take_look(
&self,
print_id: PrintId,
waited: Duration,
arrived: Vec<Arrival>,
) -> Result<Look, CoreError> {
let url = self
.config()
.camera_snapshot_url
.as_ref()
.map(|url| url.as_str().to_owned());
let fetched = match &url {
Some(url) => Some(self.fetch_frame(url).await),
None => None,
};
let written = match &fetched {
Some(Frame::Degraded(degraded)) => self.write_degraded_down(print_id, degraded).await,
_ => self.write_look_down(print_id, waited, &arrived).await,
};
let (print, mut event) = match written {
Ok(written) => written,
Err(error) => {
self.inboxes().put_back(print_id, arrived);
return Err(error);
}
};
let arrived: Vec<EventRecord> = arrived.into_iter().map(|each| each.event).collect();
let frame = match (fetched, url) {
(Some(fetched), Some(url)) => self.keep_frame(print.id, &event, url, fetched).await,
_ => None,
};
let image_path = match &frame {
Some(reference) => self.image_path(reference).await,
None => None,
};
event.image.clone_from(&frame);
let printer = self.read_snapshot().await.ok();
let job = self.read_job().await.ok();
if let Some(job) = &job
&& print.ended_at.is_none()
{
let _ = self
.record_position_from(&print, job, self.clock().now())
.await;
}
let detector_paused = self.detector_paused(print.id)
&& printer
.as_ref()
.is_some_and(|taken| taken.connection == PrinterState::Paused);
Ok(Look {
event,
arrived,
frame,
image_path,
printer,
job,
detector_paused,
})
}
async fn write_degraded_down(
&self,
print_id: PrintId,
degraded: &CameraDegradedPayload,
) -> Result<(crate::records::PrintRecord, EventRecord), CoreError> {
let print = self
.stores()
.prints
.print(print_id)
.await?
.ok_or(CoreError::NoSuchPrint { print_id })?;
let event = self
.append_system_event(print.id, EventBody::of(degraded)?)
.await?;
Ok((print, event))
}
async fn write_look_down(
&self,
print_id: PrintId,
waited: Duration,
arrived: &[Arrival],
) -> Result<(crate::records::PrintRecord, EventRecord), CoreError> {
let print = self
.stores()
.prints
.print(print_id)
.await?
.ok_or(CoreError::NoSuchPrint { print_id })?;
let payload = CameraLookPayload {
waited_s: u32::try_from(waited.as_secs()).unwrap_or(u32::MAX),
delivered: arrived.iter().map(|each| each.event.id).collect(),
};
let event = self
.append_system_event(print.id, EventBody::of(&payload)?)
.await?;
Ok((print, event))
}
pub(crate) async fn fetch_frame(&self, url: &str) -> Frame {
let mut faults: Vec<FrameFault> = Vec::new();
while faults.len() < FRAME_ATTEMPTS as usize {
let fetched = match self.vision().fetch_image(url.to_owned()).await {
Ok(fetched) => fetched,
Err(error) => return Frame::Failed(error.to_string()),
};
match self.vision().judge_frame(fetched).await {
Ok(good) => return Frame::Good(good),
Err(fault) => faults.push(fault),
}
}
let cause = match faults.last() {
Some(FrameFault::Undecodable { .. }) => FrameCause::Undecodable,
_ => FrameCause::Blank,
};
let detail = faults
.iter()
.enumerate()
.map(|(index, fault)| format!("frame {}: {fault}", index + 1))
.collect::<Vec<_>>()
.join("; ");
Frame::Degraded(CameraDegradedPayload {
attempts: FRAME_ATTEMPTS,
cause,
detail,
})
}
pub(crate) async fn keep_frame(
&self,
print_id: PrintId,
event: &EventRecord,
url: String,
fetched: Frame,
) -> Option<ImageRef> {
let image = match fetched {
Frame::Good(image) => image,
Frame::Failed(detail) => {
self.record_port_failure(print_id, event.id, PortFailureSite::CameraLook, detail)
.await;
return None;
}
Frame::Degraded(_) => return None,
};
match self
.stores()
.images
.put_image(
print_id,
event.id,
Some(url),
image.content_type,
image.bytes,
)
.await
{
Ok(record) => Some(ImageRef {
id: record.id,
sha256: record.sha256,
}),
Err(error) => {
self.record_port_failure(
print_id,
event.id,
PortFailureSite::CameraLook,
error.to_string(),
)
.await;
None
}
}
}
}
pub const FRAME_ATTEMPTS: u32 = 3;
#[derive(Debug)]
pub(crate) enum Frame {
Good(FetchedImage),
Failed(String),
Degraded(CameraDegradedPayload),
}