1use 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#[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 NoFrame,
36 LookFailed,
38 FrameMismatch,
40 NoCalibration,
43 Unjudgeable,
45}
46
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
54#[serde(crate = "printobserver_types::serde")]
55#[schemars(crate = "printobserver_types::schemars")]
56pub struct CameraCheck {
57 pub id: CameraCheckId,
59 pub checked_at: Timestamp,
61 pub sheet: SheetId,
63 pub verdict: CameraCheckVerdict,
65 pub unavailable_reason: Option<UnavailableReason>,
67 pub unjudgeable_cause: Option<UnjudgeableCause>,
70 pub offset_px: Option<f64>,
73 pub residual_px: Option<f64>,
76 pub offset_limit_px: f64,
78 pub residual_limit_px: f64,
80 #[schemars(range(min = 0))]
83 pub landmarks_moved: Option<u32>,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub correction: Option<ViewCorrection>,
89 pub bed_z_mm: f64,
91 pub frame: Option<ImageRef>,
93 pub image_path: Option<PathBuf>,
96 pub message: String,
98}
99
100#[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 pub camera_check: CameraCheck,
107}
108
109impl EventPayload for CameraCheckedPayload {
110 const KIND: &'static str = CAMERA_CHECKED_KIND;
111}
112
113#[derive(Debug, Clone, PartialEq, Deserialize)]
115#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
116pub struct CheckCameraQuery {
117 pub sheet: String,
119 pub bed_z_mm: f64,
122}
123
124#[derive(Debug, Clone)]
126pub struct Asked {
127 pub id: CameraCheckId,
129 pub checked_at: Timestamp,
131 pub sheet: SheetId,
133 pub bed_z_mm: f64,
135}
136
137impl Asked {
138 #[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 #[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 (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 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 #[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}