use std::path::PathBuf;
use printobserver_core::{CAMERA_CHECKED_KIND, CameraCheckId, CameraCheckVerdict, SheetId};
use printobserver_panels::sheet::{MAX_RESIDUAL_PX, SHEET_TOLERANCE_PX};
use printobserver_panels::{SheetFit, SheetVerdict, UnjudgeableCause, ViewCorrection};
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{EventPayload, ImageRef, Timestamp};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum UnavailableReason {
NoFrame,
LookFailed,
FrameMismatch,
NoCalibration,
Unjudgeable,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CameraCheck {
pub id: CameraCheckId,
pub checked_at: Timestamp,
pub sheet: SheetId,
pub verdict: CameraCheckVerdict,
pub unavailable_reason: Option<UnavailableReason>,
pub unjudgeable_cause: Option<UnjudgeableCause>,
pub offset_px: Option<f64>,
pub residual_px: Option<f64>,
pub offset_limit_px: f64,
pub residual_limit_px: f64,
#[schemars(range(min = 0))]
pub landmarks_moved: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub correction: Option<ViewCorrection>,
pub bed_z_mm: f64,
pub frame: Option<ImageRef>,
pub image_path: Option<PathBuf>,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CameraCheckedPayload {
pub camera_check: CameraCheck,
}
impl EventPayload for CameraCheckedPayload {
const KIND: &'static str = CAMERA_CHECKED_KIND;
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
pub struct CheckCameraQuery {
pub sheet: String,
pub bed_z_mm: f64,
}
#[derive(Debug, Clone)]
pub struct Asked {
pub id: CameraCheckId,
pub checked_at: Timestamp,
pub sheet: SheetId,
pub bed_z_mm: f64,
}
impl Asked {
#[must_use]
pub fn camera_unavailable(
self,
reason: UnavailableReason,
detail: &str,
frame: Option<(ImageRef, PathBuf)>,
) -> CameraCheck {
let message = match reason {
UnavailableReason::NoFrame => format!(
"The camera is unavailable: it gave no frame ({detail}); check that it is \
connected and streaming, then check again."
),
UnavailableReason::LookFailed => format!(
"The camera is unavailable: the look failed ({detail}); check that it can be \
reached, then check again."
),
UnavailableReason::NoCalibration => "The camera cannot be checked: no calibration \
is configured for this camera; deploy this printer's calibration in the server's \
`[camera] calibration`, or run a calibration to create one, then check again."
.to_owned(),
UnavailableReason::FrameMismatch | UnavailableReason::Unjudgeable => format!(
"The camera is unavailable for this check: {detail}; check that the camera \
configured is the camera and stream this printer was set up with, then check \
again."
),
};
let (frame, image_path) = frame.unzip();
CameraCheck {
verdict: CameraCheckVerdict::Unavailable,
unavailable_reason: Some(reason),
frame,
image_path,
..self.blank(message)
}
}
#[must_use]
pub fn judged(
self,
fit: &SheetFit,
drift_tolerance_px: f64,
frame: ImageRef,
image_path: PathBuf,
) -> CameraCheck {
let sheet = self.sheet.as_str().to_owned();
let moved = fit.landmarks_moved;
let offset = fit.offset_px();
let message = match (fit.verdict, offset) {
(SheetVerdict::Aligned, Some(offset)) => format!(
"The camera is aligned with its calibration on the {sheet} sheet: the sheet \
sits {offset:.1} px from where the calibration draws it, within \
{SHEET_TOLERANCE_PX:.0} px; name this check as the manifest's `camera_check` \
when starting the print on this sheet."
),
(SheetVerdict::NotAligned, _) if moved >= 2 => format!(
"The camera has moved since its calibration: {moved} of its landmarks lie beyond \
{drift_tolerance_px:.0} px of where it was calibrated{}; run a calibration \
before printing.",
if offset.is_none() {
", though the sheet could not be fitted to show by how much"
} else {
""
}
),
(SheetVerdict::NotAligned, Some(offset)) => format!(
"The camera is not aligned with its calibration: the {sheet} sheet sits \
{offset:.1} px from where the calibration draws it, beyond the \
{SHEET_TOLERANCE_PX:.0} px an aligned camera may be off; run a calibration \
before printing."
),
(SheetVerdict::Unjudgeable(cause), _) => format!(
"The frame cannot show whether the camera is aligned: {}; check that the \
{sheet} sheet is seated and the camera's view of it is clear, then check again.",
cause.said()
),
(SheetVerdict::Aligned | SheetVerdict::NotAligned, None) => format!(
"The frame cannot show whether the camera is aligned: the sheet could not be \
fitted; check that the {sheet} sheet is seated and the camera's view of it is \
clear, then check again."
),
};
let (verdict, unavailable_reason, unjudgeable_cause) = match (fit.verdict, offset) {
(SheetVerdict::Aligned, Some(_)) => (CameraCheckVerdict::Aligned, None, None),
(SheetVerdict::NotAligned, _) if moved >= 2 => {
(CameraCheckVerdict::NotAligned, None, None)
}
(SheetVerdict::NotAligned, Some(_)) => (CameraCheckVerdict::NotAligned, None, None),
(SheetVerdict::Unjudgeable(cause), _) => (
CameraCheckVerdict::Unavailable,
Some(UnavailableReason::Unjudgeable),
Some(cause),
),
(SheetVerdict::Aligned | SheetVerdict::NotAligned, None) => (
CameraCheckVerdict::Unavailable,
Some(UnavailableReason::Unjudgeable),
Some(UnjudgeableCause::NoSheetFound),
),
};
CameraCheck {
verdict,
unavailable_reason,
unjudgeable_cause,
offset_px: offset,
residual_px: fit.residual_px,
landmarks_moved: Some(u32::try_from(moved).unwrap_or(u32::MAX)),
correction: (verdict == CameraCheckVerdict::Aligned)
.then(|| fit.correction.clone())
.flatten(),
frame: Some(frame),
image_path: Some(image_path),
..self.blank(message)
}
}
fn blank(self, message: String) -> CameraCheck {
CameraCheck {
id: self.id,
checked_at: self.checked_at,
sheet: self.sheet,
verdict: CameraCheckVerdict::Unavailable,
unavailable_reason: None,
unjudgeable_cause: None,
offset_px: None,
residual_px: None,
offset_limit_px: SHEET_TOLERANCE_PX,
residual_limit_px: MAX_RESIDUAL_PX,
landmarks_moved: None,
correction: None,
bed_z_mm: self.bed_z_mm,
frame: None,
image_path: None,
message,
}
}
}
impl Sample for CameraCheck {
fn sample_full() -> Self {
Self {
id: CameraCheckId::sample_full(),
checked_at: Timestamp::sample_full(),
sheet: SheetId::try_from("smooth-pei".to_owned()).expect("a sheet"),
verdict: CameraCheckVerdict::Aligned,
unavailable_reason: None,
unjudgeable_cause: None,
offset_px: Some(3.1),
residual_px: Some(1.6),
offset_limit_px: SHEET_TOLERANCE_PX,
residual_limit_px: MAX_RESIDUAL_PX,
landmarks_moved: Some(0),
correction: Some(ViewCorrection::translation(
[-1.6, 2.6],
vec![printobserver_panels::ReferenceLandmark {
name: "frame-screws-right-front".to_owned(),
offset_px: [0.2, -0.1],
score: 0.93,
}],
)),
bed_z_mm: 30.0,
frame: Some(ImageRef::sample_full()),
image_path: Some(PathBuf::from(
"/var/lib/printobserver/check-images/camera-check.jpg",
)),
message: "The camera is aligned with its calibration on the smooth-pei sheet."
.to_owned(),
}
}
fn sample_minimal() -> Self {
Self {
verdict: CameraCheckVerdict::Unavailable,
unavailable_reason: Some(UnavailableReason::NoFrame),
offset_px: None,
residual_px: None,
landmarks_moved: None,
correction: None,
frame: None,
image_path: None,
message: "The camera is unavailable: it gave no frame.".to_owned(),
..Self::sample_full()
}
}
fn sample_alternates() -> Vec<Self> {
vec![
Self {
verdict: CameraCheckVerdict::NotAligned,
landmarks_moved: Some(4),
correction: None,
..Self::sample_full()
},
Self {
verdict: CameraCheckVerdict::Unavailable,
unavailable_reason: Some(UnavailableReason::Unjudgeable),
unjudgeable_cause: Some(UnjudgeableCause::SheetOccluded),
offset_px: None,
residual_px: None,
correction: None,
..Self::sample_full()
},
]
}
}
impl Sample for CameraCheckedPayload {
fn sample_full() -> Self {
Self {
camera_check: CameraCheck::sample_full(),
}
}
fn sample_minimal() -> Self {
Self {
camera_check: CameraCheck::sample_minimal(),
}
}
}
impl Sample for UnavailableReason {
fn sample_full() -> Self {
Self::Unjudgeable
}
fn sample_alternates() -> Vec<Self> {
vec![
Self::NoFrame,
Self::LookFailed,
Self::FrameMismatch,
Self::NoCalibration,
]
}
}
#[cfg(test)]
mod tests {
use printobserver_core::camera_check::standing_of;
use printobserver_types::contract::Sample as _;
use printobserver_types::{EventBody, EventRecord};
use super::CameraCheckedPayload;
#[test]
fn a_start_reads_the_check_this_server_writes() {
let payload = CameraCheckedPayload::sample_full();
let event = EventRecord {
body: EventBody::of(&payload).expect("the payload renders"),
..EventRecord::sample_full()
};
let read = standing_of(&event).expect("the check reads back");
assert_eq!(read.id, payload.camera_check.id);
assert_eq!(read.sheet, payload.camera_check.sheet);
assert_eq!(read.verdict, payload.camera_check.verdict);
}
}