printobserver-server 0.20.1

The printobserver server.
Documentation
//! The camera check: one fresh look at the empty build sheet, judged against
//! the printer's calibration, before anything is printed.
//!
//! The operator asks for it naming the sheet on the bed and the bed's height
//! as the printer read it back while idle ([`CheckCameraQuery`]); it takes one
//! look, sends nothing to the printer, starts no agent turn and changes no
//! print. What it found is answered and kept as a [`CameraCheck`], written into
//! the printer timeline as a `camera_checked` event ([`CameraCheckedPayload`]),
//! and a start may name an `aligned` one, so its print is drawn through the
//! check's correction from its first check rather than once its first layer is
//! clearly found.
//!
//! The verdict is [`printobserver_panels::sheet`]'s, and what is said of it is
//! chosen for what the operator does next: a camera that moved is sent to a
//! calibration run, even when the sheet could not be fitted, while a camera
//! that gave no frame, or a frame that cannot show whether it moved, is never
//! sent to one.

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};

/// Why a camera check could not say whether the camera is aligned.
#[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 {
    /// The camera gave no frame.
    NoFrame,
    /// The look failed or timed out.
    LookFailed,
    /// The frame is not the calibration's size or stream.
    FrameMismatch,
    /// No calibration is configured for this camera, so no frame can be held
    /// to one.
    NoCalibration,
    /// The fit could not judge the frame.
    Unjudgeable,
}

/// One check of the camera's alignment with its calibration, on the empty
/// sheet: the answer to `check_camera` and the record a start names.
///
/// An answer, so it admits fields beside its own the way every answer of the
/// server does: a client that could not open `image_path` says so in a field
/// of its own beside the rest.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CameraCheck {
    /// The check.
    pub id: CameraCheckId,
    /// When it was made.
    pub checked_at: Timestamp,
    /// The sheet it was made on.
    pub sheet: SheetId,
    /// What it found.
    pub verdict: CameraCheckVerdict,
    /// Why it could not say; null unless the verdict is `unavailable`.
    pub unavailable_reason: Option<UnavailableReason>,
    /// What the fit could not judge; null unless the reason is `unjudgeable`,
    /// so never set on a frame whose landmarks show the camera moved.
    pub unjudgeable_cause: Option<UnjudgeableCause>,
    /// The fitted translation's length, in pixels; null when the sheet could
    /// not be fitted.
    pub offset_px: Option<f64>,
    /// The RMS distance of the sheet's found edges from the translated
    /// outline, in pixels; null when the sheet could not be fitted.
    pub residual_px: Option<f64>,
    /// The translation `aligned` is held to, in pixels.
    pub offset_limit_px: f64,
    /// The residual above which the frame is unjudgeable, in pixels.
    pub residual_limit_px: f64,
    /// How many visible landmarks lie beyond the calibration's drift
    /// tolerance; null when there was no frame of the calibration's to search.
    #[schemars(range(min = 0))]
    pub landmarks_moved: Option<u32>,
    /// The correction a print started under this check is drawn through,
    /// its reference the landmarks found on this frame; present only when
    /// `aligned`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub correction: Option<ViewCorrection>,
    /// The bed's height the check was judged at, as given, in millimetres.
    pub bed_z_mm: f64,
    /// The stored frame; null when there is none.
    pub frame: Option<ImageRef>,
    /// The absolute path, on the server's host, of the frame with the fitted
    /// sheet outline and the landmarks drawn; null when there is no frame.
    pub image_path: Option<PathBuf>,
    /// What was found and what to do next, in one sentence.
    pub message: String,
}

/// One camera check, written into the printer timeline.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CameraCheckedPayload {
    /// The check, as it was answered.
    pub camera_check: CameraCheck,
}

impl EventPayload for CameraCheckedPayload {
    const KIND: &'static str = CAMERA_CHECKED_KIND;
}

/// What `check_camera` is asked, after the question mark.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
pub struct CheckCameraQuery {
    /// The sheet on the bed.
    pub sheet: String,
    /// The bed's height, read back from the printer with `M114` while idle,
    /// in millimetres.
    pub bed_z_mm: f64,
}

/// What a check is made of before its frame is judged.
#[derive(Debug, Clone)]
pub struct Asked {
    /// The check's identifier.
    pub id: CameraCheckId,
    /// When it was made.
    pub checked_at: Timestamp,
    /// The sheet.
    pub sheet: SheetId,
    /// The bed's height.
    pub bed_z_mm: f64,
}

impl Asked {
    /// The check answered `unavailable` for a reason that is the camera's:
    /// no frame, a failed look, or a frame of another size or stream.
    #[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)
        }
    }

    /// The check of a frame the fit judged, its drawn frame at `image_path`.
    #[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()
            ),
            // A verdict the fit reaches only with an offset, answered as the
            // frame it could not judge.
            (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)
        }
    }

    /// A check carrying nothing measured, saying `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;

    /// What a start reads of a check is read off the very record this server
    /// writes: its identifier, its sheet and its verdict.
    #[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);
    }
}