Skip to main content

printobserver_server/
camera_check.rs

1//! The camera check: one fresh look at the empty build sheet, judged against
2//! the printer's calibration, before anything is printed.
3//!
4//! The operator asks for it naming the sheet on the bed and the bed's height
5//! as the printer read it back while idle ([`CheckCameraQuery`]); it takes one
6//! look, sends nothing to the printer, starts no agent turn and changes no
7//! print. What it found is answered and kept as a [`CameraCheck`], written into
8//! the printer timeline as a `camera_checked` event ([`CameraCheckedPayload`]),
9//! and a start may name an `aligned` one, so its print is drawn through the
10//! check's correction from its first check rather than once its first layer is
11//! clearly found.
12//!
13//! The verdict is [`printobserver_panels::sheet`]'s, and what is said of it is
14//! chosen for what the operator does next: a camera that moved is sent to a
15//! calibration run, even when the sheet could not be fitted, while a camera
16//! that gave no frame, or a frame that cannot show whether it moved, is never
17//! sent to one.
18
19use std::path::PathBuf;
20
21use printobserver_core::{CAMERA_CHECKED_KIND, CameraCheckId, CameraCheckVerdict, SheetId};
22use printobserver_panels::sheet::{MAX_RESIDUAL_PX, SHEET_TOLERANCE_PX};
23use printobserver_panels::{SheetFit, SheetVerdict, UnjudgeableCause, ViewCorrection};
24use printobserver_types::contract::Sample;
25use printobserver_types::schemars::JsonSchema;
26use printobserver_types::serde::{Deserialize, Serialize};
27use printobserver_types::{EventPayload, ImageRef, Timestamp};
28
29/// Why a camera check could not say whether the camera is aligned.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
31#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
32#[schemars(crate = "printobserver_types::schemars")]
33pub enum UnavailableReason {
34    /// The camera gave no frame.
35    NoFrame,
36    /// The look failed or timed out.
37    LookFailed,
38    /// The frame is not the calibration's size or stream.
39    FrameMismatch,
40    /// No calibration is configured for this camera, so no frame can be held
41    /// to one.
42    NoCalibration,
43    /// The fit could not judge the frame.
44    Unjudgeable,
45}
46
47/// One check of the camera's alignment with its calibration, on the empty
48/// sheet: the answer to `check_camera` and the record a start names.
49///
50/// An answer, so it admits fields beside its own the way every answer of the
51/// server does: a client that could not open `image_path` says so in a field
52/// of its own beside the rest.
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
54#[serde(crate = "printobserver_types::serde")]
55#[schemars(crate = "printobserver_types::schemars")]
56pub struct CameraCheck {
57    /// The check.
58    pub id: CameraCheckId,
59    /// When it was made.
60    pub checked_at: Timestamp,
61    /// The sheet it was made on.
62    pub sheet: SheetId,
63    /// What it found.
64    pub verdict: CameraCheckVerdict,
65    /// Why it could not say; null unless the verdict is `unavailable`.
66    pub unavailable_reason: Option<UnavailableReason>,
67    /// What the fit could not judge; null unless the reason is `unjudgeable`,
68    /// so never set on a frame whose landmarks show the camera moved.
69    pub unjudgeable_cause: Option<UnjudgeableCause>,
70    /// The fitted translation's length, in pixels; null when the sheet could
71    /// not be fitted.
72    pub offset_px: Option<f64>,
73    /// The RMS distance of the sheet's found edges from the translated
74    /// outline, in pixels; null when the sheet could not be fitted.
75    pub residual_px: Option<f64>,
76    /// The translation `aligned` is held to, in pixels.
77    pub offset_limit_px: f64,
78    /// The residual above which the frame is unjudgeable, in pixels.
79    pub residual_limit_px: f64,
80    /// How many visible landmarks lie beyond the calibration's drift
81    /// tolerance; null when there was no frame of the calibration's to search.
82    #[schemars(range(min = 0))]
83    pub landmarks_moved: Option<u32>,
84    /// The correction a print started under this check is drawn through,
85    /// its reference the landmarks found on this frame; present only when
86    /// `aligned`.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub correction: Option<ViewCorrection>,
89    /// The bed's height the check was judged at, as given, in millimetres.
90    pub bed_z_mm: f64,
91    /// The stored frame; null when there is none.
92    pub frame: Option<ImageRef>,
93    /// The absolute path, on the server's host, of the frame with the fitted
94    /// sheet outline and the landmarks drawn; null when there is no frame.
95    pub image_path: Option<PathBuf>,
96    /// What was found and what to do next, in one sentence.
97    pub message: String,
98}
99
100/// One camera check, written into the printer timeline.
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
102#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
103#[schemars(crate = "printobserver_types::schemars")]
104pub struct CameraCheckedPayload {
105    /// The check, as it was answered.
106    pub camera_check: CameraCheck,
107}
108
109impl EventPayload for CameraCheckedPayload {
110    const KIND: &'static str = CAMERA_CHECKED_KIND;
111}
112
113/// What `check_camera` is asked, after the question mark.
114#[derive(Debug, Clone, PartialEq, Deserialize)]
115#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
116pub struct CheckCameraQuery {
117    /// The sheet on the bed.
118    pub sheet: String,
119    /// The bed's height, read back from the printer with `M114` while idle,
120    /// in millimetres.
121    pub bed_z_mm: f64,
122}
123
124/// What a check is made of before its frame is judged.
125#[derive(Debug, Clone)]
126pub struct Asked {
127    /// The check's identifier.
128    pub id: CameraCheckId,
129    /// When it was made.
130    pub checked_at: Timestamp,
131    /// The sheet.
132    pub sheet: SheetId,
133    /// The bed's height.
134    pub bed_z_mm: f64,
135}
136
137impl Asked {
138    /// The check answered `unavailable` for a reason that is the camera's:
139    /// no frame, a failed look, or a frame of another size or stream.
140    #[must_use]
141    pub fn camera_unavailable(
142        self,
143        reason: UnavailableReason,
144        detail: &str,
145        frame: Option<(ImageRef, PathBuf)>,
146    ) -> CameraCheck {
147        let message = match reason {
148            UnavailableReason::NoFrame => format!(
149                "The camera is unavailable: it gave no frame ({detail}); check that it is \
150                 connected and streaming, then check again."
151            ),
152            UnavailableReason::LookFailed => format!(
153                "The camera is unavailable: the look failed ({detail}); check that it can be \
154                 reached, then check again."
155            ),
156            UnavailableReason::NoCalibration => "The camera cannot be checked: no calibration \
157                 is configured for this camera; deploy this printer's calibration in the server's \
158                 `[camera] calibration`, or run a calibration to create one, then check again."
159                .to_owned(),
160            UnavailableReason::FrameMismatch | UnavailableReason::Unjudgeable => format!(
161                "The camera is unavailable for this check: {detail}; check that the camera \
162                 configured is the camera and stream this printer was set up with, then check \
163                 again."
164            ),
165        };
166        let (frame, image_path) = frame.unzip();
167        CameraCheck {
168            verdict: CameraCheckVerdict::Unavailable,
169            unavailable_reason: Some(reason),
170            frame,
171            image_path,
172            ..self.blank(message)
173        }
174    }
175
176    /// The check of a frame the fit judged, its drawn frame at `image_path`.
177    #[must_use]
178    pub fn judged(
179        self,
180        fit: &SheetFit,
181        drift_tolerance_px: f64,
182        frame: ImageRef,
183        image_path: PathBuf,
184    ) -> CameraCheck {
185        let sheet = self.sheet.as_str().to_owned();
186        let moved = fit.landmarks_moved;
187        let offset = fit.offset_px();
188        let message = match (fit.verdict, offset) {
189            (SheetVerdict::Aligned, Some(offset)) => format!(
190                "The camera is aligned with its calibration on the {sheet} sheet: the sheet \
191                 sits {offset:.1} px from where the calibration draws it, within \
192                 {SHEET_TOLERANCE_PX:.0} px; name this check as the manifest's `camera_check` \
193                 when starting the print on this sheet."
194            ),
195            (SheetVerdict::NotAligned, _) if moved >= 2 => format!(
196                "The camera has moved since its calibration: {moved} of its landmarks lie beyond \
197                 {drift_tolerance_px:.0} px of where it was calibrated{}; run a calibration \
198                 before printing.",
199                if offset.is_none() {
200                    ", though the sheet could not be fitted to show by how much"
201                } else {
202                    ""
203                }
204            ),
205            (SheetVerdict::NotAligned, Some(offset)) => format!(
206                "The camera is not aligned with its calibration: the {sheet} sheet sits \
207                 {offset:.1} px from where the calibration draws it, beyond the \
208                 {SHEET_TOLERANCE_PX:.0} px an aligned camera may be off; run a calibration \
209                 before printing."
210            ),
211            (SheetVerdict::Unjudgeable(cause), _) => format!(
212                "The frame cannot show whether the camera is aligned: {}; check that the \
213                 {sheet} sheet is seated and the camera's view of it is clear, then check again.",
214                cause.said()
215            ),
216            // A verdict the fit reaches only with an offset, answered as the
217            // frame it could not judge.
218            (SheetVerdict::Aligned | SheetVerdict::NotAligned, None) => format!(
219                "The frame cannot show whether the camera is aligned: the sheet could not be \
220                 fitted; check that the {sheet} sheet is seated and the camera's view of it is \
221                 clear, then check again."
222            ),
223        };
224        let (verdict, unavailable_reason, unjudgeable_cause) = match (fit.verdict, offset) {
225            (SheetVerdict::Aligned, Some(_)) => (CameraCheckVerdict::Aligned, None, None),
226            (SheetVerdict::NotAligned, _) if moved >= 2 => {
227                (CameraCheckVerdict::NotAligned, None, None)
228            }
229            (SheetVerdict::NotAligned, Some(_)) => (CameraCheckVerdict::NotAligned, None, None),
230            (SheetVerdict::Unjudgeable(cause), _) => (
231                CameraCheckVerdict::Unavailable,
232                Some(UnavailableReason::Unjudgeable),
233                Some(cause),
234            ),
235            (SheetVerdict::Aligned | SheetVerdict::NotAligned, None) => (
236                CameraCheckVerdict::Unavailable,
237                Some(UnavailableReason::Unjudgeable),
238                Some(UnjudgeableCause::NoSheetFound),
239            ),
240        };
241        CameraCheck {
242            verdict,
243            unavailable_reason,
244            unjudgeable_cause,
245            offset_px: offset,
246            residual_px: fit.residual_px,
247            landmarks_moved: Some(u32::try_from(moved).unwrap_or(u32::MAX)),
248            correction: (verdict == CameraCheckVerdict::Aligned)
249                .then(|| fit.correction.clone())
250                .flatten(),
251            frame: Some(frame),
252            image_path: Some(image_path),
253            ..self.blank(message)
254        }
255    }
256
257    /// A check carrying nothing measured, saying `message`.
258    fn blank(self, message: String) -> CameraCheck {
259        CameraCheck {
260            id: self.id,
261            checked_at: self.checked_at,
262            sheet: self.sheet,
263            verdict: CameraCheckVerdict::Unavailable,
264            unavailable_reason: None,
265            unjudgeable_cause: None,
266            offset_px: None,
267            residual_px: None,
268            offset_limit_px: SHEET_TOLERANCE_PX,
269            residual_limit_px: MAX_RESIDUAL_PX,
270            landmarks_moved: None,
271            correction: None,
272            bed_z_mm: self.bed_z_mm,
273            frame: None,
274            image_path: None,
275            message,
276        }
277    }
278}
279
280impl Sample for CameraCheck {
281    fn sample_full() -> Self {
282        Self {
283            id: CameraCheckId::sample_full(),
284            checked_at: Timestamp::sample_full(),
285            sheet: SheetId::try_from("smooth-pei".to_owned()).expect("a sheet"),
286            verdict: CameraCheckVerdict::Aligned,
287            unavailable_reason: None,
288            unjudgeable_cause: None,
289            offset_px: Some(3.1),
290            residual_px: Some(1.6),
291            offset_limit_px: SHEET_TOLERANCE_PX,
292            residual_limit_px: MAX_RESIDUAL_PX,
293            landmarks_moved: Some(0),
294            correction: Some(ViewCorrection::translation(
295                [-1.6, 2.6],
296                vec![printobserver_panels::ReferenceLandmark {
297                    name: "frame-screws-right-front".to_owned(),
298                    offset_px: [0.2, -0.1],
299                    score: 0.93,
300                }],
301            )),
302            bed_z_mm: 30.0,
303            frame: Some(ImageRef::sample_full()),
304            image_path: Some(PathBuf::from(
305                "/var/lib/printobserver/check-images/camera-check.jpg",
306            )),
307            message: "The camera is aligned with its calibration on the smooth-pei sheet."
308                .to_owned(),
309        }
310    }
311
312    fn sample_minimal() -> Self {
313        Self {
314            verdict: CameraCheckVerdict::Unavailable,
315            unavailable_reason: Some(UnavailableReason::NoFrame),
316            offset_px: None,
317            residual_px: None,
318            landmarks_moved: None,
319            correction: None,
320            frame: None,
321            image_path: None,
322            message: "The camera is unavailable: it gave no frame.".to_owned(),
323            ..Self::sample_full()
324        }
325    }
326
327    fn sample_alternates() -> Vec<Self> {
328        vec![
329            Self {
330                verdict: CameraCheckVerdict::NotAligned,
331                landmarks_moved: Some(4),
332                correction: None,
333                ..Self::sample_full()
334            },
335            Self {
336                verdict: CameraCheckVerdict::Unavailable,
337                unavailable_reason: Some(UnavailableReason::Unjudgeable),
338                unjudgeable_cause: Some(UnjudgeableCause::SheetOccluded),
339                offset_px: None,
340                residual_px: None,
341                correction: None,
342                ..Self::sample_full()
343            },
344        ]
345    }
346}
347
348impl Sample for CameraCheckedPayload {
349    fn sample_full() -> Self {
350        Self {
351            camera_check: CameraCheck::sample_full(),
352        }
353    }
354
355    fn sample_minimal() -> Self {
356        Self {
357            camera_check: CameraCheck::sample_minimal(),
358        }
359    }
360}
361
362impl Sample for UnavailableReason {
363    fn sample_full() -> Self {
364        Self::Unjudgeable
365    }
366
367    fn sample_alternates() -> Vec<Self> {
368        vec![
369            Self::NoFrame,
370            Self::LookFailed,
371            Self::FrameMismatch,
372            Self::NoCalibration,
373        ]
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use printobserver_core::camera_check::standing_of;
380    use printobserver_types::contract::Sample as _;
381    use printobserver_types::{EventBody, EventRecord};
382
383    use super::CameraCheckedPayload;
384
385    /// What a start reads of a check is read off the very record this server
386    /// writes: its identifier, its sheet and its verdict.
387    #[test]
388    fn a_start_reads_the_check_this_server_writes() {
389        let payload = CameraCheckedPayload::sample_full();
390        let event = EventRecord {
391            body: EventBody::of(&payload).expect("the payload renders"),
392            ..EventRecord::sample_full()
393        };
394        let read = standing_of(&event).expect("the check reads back");
395        assert_eq!(read.id, payload.camera_check.id);
396        assert_eq!(read.sheet, payload.camera_check.sheet);
397        assert_eq!(read.verdict, payload.camera_check.verdict);
398    }
399}