1use std::path::{Path, PathBuf};
54use std::sync::Arc;
55use std::time::Duration;
56
57use printobserver_core::PlanPosition;
58use printobserver_core::store::PrintStore;
59use printobserver_panels::{
60 AlignmentInputs, CameraCalibration, ComposeError, FirstLayerInputs, FirstLayerVerdict,
61 FrameField, InconclusiveReason, ReferenceLandmark, ViewCorrection, ViewJudgement, ViewOutcome,
62 judge_first_layer, judge_found, landmarks_in_frame,
63};
64use printobserver_supervisor_api::{ImageFallback, ImageKind};
65use printobserver_types::contract::Sample;
66use printobserver_types::schemars::JsonSchema;
67use printobserver_types::serde::{Deserialize, Serialize};
68use printobserver_types::{EventBody, EventPayload, PrintId, Timestamp};
69
70#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
72#[serde(
73 crate = "printobserver_types::serde",
74 tag = "failure",
75 rename_all = "snake_case"
76)]
77#[schemars(crate = "printobserver_types::schemars")]
78pub enum AlignmentFailure {
79 Offset {
84 offset_px: f64,
86 },
87 Resolution {
89 expected: [u32; 2],
91 got: [u32; 2],
93 },
94 Stream,
96}
97
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
101#[serde(
102 crate = "printobserver_types::serde",
103 tag = "verdict",
104 rename_all = "snake_case"
105)]
106#[schemars(crate = "printobserver_types::schemars")]
107pub enum PrintAlignment {
108 Unavailable,
111 Pending,
114 Passed {
116 offset_px: f64,
118 #[serde(default)]
122 correction_px: [f64; 2],
123 },
124 Failed {
126 reason: AlignmentFailure,
128 },
129}
130
131impl Sample for PrintAlignment {
132 fn sample_full() -> Self {
133 Self::Passed {
134 offset_px: 14.6,
135 correction_px: [14.0, 4.0],
136 }
137 }
138
139 fn sample_minimal() -> Self {
140 Self::Pending
141 }
142
143 fn sample_alternates() -> Vec<Self> {
144 vec![
145 Self::Unavailable,
146 Self::Failed {
147 reason: AlignmentFailure::Offset { offset_px: 48.5 },
148 },
149 Self::Failed {
150 reason: AlignmentFailure::Resolution {
151 expected: [1920, 1080],
152 got: [1280, 720],
153 },
154 },
155 Self::Failed {
156 reason: AlignmentFailure::Stream,
157 },
158 ]
159 }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164#[serde(crate = "printobserver_types::serde")]
165pub struct PreviousCheck {
166 pub frame: PathBuf,
168 pub captured_at: printobserver_types::Timestamp,
170}
171
172#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174#[serde(crate = "printobserver_types::serde")]
175pub struct CheckedFrame {
176 pub frame: PathBuf,
178 pub captured_at: printobserver_types::Timestamp,
180 pub print_z_mm: f64,
182}
183
184const MAX_CHECKED_FRAMES: usize = 512;
186
187pub struct Alignments {
190 directory: PathBuf,
192 previous_directory: PathBuf,
194 checked_directory: PathBuf,
196 view_directory: PathBuf,
199 calibration: Option<Arc<CameraCalibration>>,
201 prints: Arc<dyn PrintStore>,
203}
204
205impl core::fmt::Debug for Alignments {
206 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
207 formatter
208 .debug_struct("Alignments")
209 .field("directory", &self.directory)
210 .field("calibrated", &self.calibration.is_some())
211 .finish_non_exhaustive()
212 }
213}
214
215#[must_use]
217pub fn verdict_dir(state_dir: &Path) -> PathBuf {
218 state_dir.join("alignment")
219}
220
221#[must_use]
224pub fn previous_check_dir(state_dir: &Path) -> PathBuf {
225 state_dir.join("previous-check")
226}
227
228#[must_use]
231pub fn checked_frames_dir(state_dir: &Path) -> PathBuf {
232 state_dir.join("checked-frames")
233}
234
235#[must_use]
238pub fn camera_view_dir(state_dir: &Path) -> PathBuf {
239 state_dir.join("camera-view")
240}
241
242impl Alignments {
243 pub fn new(
249 state_dir: &Path,
250 calibration: Option<Arc<CameraCalibration>>,
251 prints: Arc<dyn PrintStore>,
252 ) -> std::io::Result<Self> {
253 let directory = verdict_dir(state_dir);
254 std::fs::create_dir_all(&directory)?;
255 let previous_directory = previous_check_dir(state_dir);
256 std::fs::create_dir_all(&previous_directory)?;
257 let checked_directory = checked_frames_dir(state_dir);
258 std::fs::create_dir_all(&checked_directory)?;
259 let view_directory = camera_view_dir(state_dir);
260 std::fs::create_dir_all(&view_directory)?;
261 Ok(Self {
262 directory,
263 previous_directory,
264 checked_directory,
265 view_directory,
266 calibration,
267 prints,
268 })
269 }
270
271 fn path_of(&self, print_id: PrintId) -> PathBuf {
273 self.directory.join(format!("{print_id}.json"))
274 }
275
276 #[must_use]
278 pub fn calibration(&self) -> Option<&CameraCalibration> {
279 self.calibration.as_deref()
280 }
281
282 fn previous_path_of(&self, print_id: PrintId) -> PathBuf {
284 self.previous_directory.join(format!("{print_id}.json"))
285 }
286
287 #[must_use]
290 pub fn previous_check(&self, print_id: PrintId) -> Option<PreviousCheck> {
291 std::fs::read(self.previous_path_of(print_id))
292 .ok()
293 .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
294 }
295
296 pub fn record_check(&self, print_id: PrintId, check: &PreviousCheck) {
307 let Ok(bytes) = printobserver_types::serde_json::to_vec(check) else {
308 return;
309 };
310 if let Err(error) = replace_file(&self.previous_path_of(print_id), &bytes) {
311 eprintln!(
312 "printobserver: print {print_id}: the last check's frame could not be recorded, so the next check shows an older one or none: {error}"
313 );
314 }
315 }
316
317 fn checked_path_of(&self, print_id: PrintId) -> PathBuf {
319 self.checked_directory.join(format!("{print_id}.json"))
320 }
321
322 #[must_use]
326 pub fn checked_frames(&self, print_id: PrintId) -> Vec<CheckedFrame> {
327 std::fs::read(self.checked_path_of(print_id))
328 .ok()
329 .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
330 .unwrap_or_default()
331 }
332
333 pub fn restart_growth(&self, print_id: PrintId) {
340 let path = self.checked_path_of(print_id);
341 if let Err(error) = std::fs::remove_file(&path)
342 && error.kind() != std::io::ErrorKind::NotFound
343 {
344 eprintln!(
345 "printobserver: print {print_id}: its checked frames could not be forgotten after a planned change, so a later check may measure growth across the wait: {error}"
346 );
347 }
348 }
349
350 #[must_use]
353 pub fn growth_reference(
354 &self,
355 print_id: PrintId,
356 print_z_mm: f64,
357 rise_mm: f64,
358 ) -> Option<CheckedFrame> {
359 reference_in(&self.checked_frames(print_id), print_z_mm, rise_mm).cloned()
360 }
361
362 pub fn record_checked_frame(&self, print_id: PrintId, checked: CheckedFrame, rise_mm: f64) {
371 let kept = kept_with(self.checked_frames(print_id), checked, rise_mm);
372 let Ok(bytes) = printobserver_types::serde_json::to_vec(&kept) else {
373 return;
374 };
375 if let Err(error) = replace_file(&self.checked_path_of(print_id), &bytes) {
376 eprintln!(
377 "printobserver: print {print_id}: a check's frame and height could not be recorded, so a later check measures growth from an older one or none: {error}"
378 );
379 }
380 }
381
382 #[must_use]
384 pub fn print_alignment(&self, print_id: PrintId) -> PrintAlignment {
385 if self.calibration.is_none() {
386 return PrintAlignment::Unavailable;
387 }
388 match std::fs::read(self.path_of(print_id))
389 .ok()
390 .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
391 {
392 Some(PrintAlignment::Failed {
395 reason: AlignmentFailure::Offset { .. },
396 })
397 | None => PrintAlignment::Pending,
398 Some(verdict) => verdict,
399 }
400 }
401
402 fn view_path_of(&self, print_id: PrintId) -> PathBuf {
404 self.view_directory.join(format!("{print_id}.json"))
405 }
406
407 fn view_state(&self, print_id: PrintId) -> CameraViewState {
410 std::fs::read(self.view_path_of(print_id))
411 .ok()
412 .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
413 .unwrap_or_default()
414 }
415
416 fn keep_view_state(&self, print_id: PrintId, state: &CameraViewState) {
420 let Ok(bytes) = printobserver_types::serde_json::to_vec(state) else {
421 return;
422 };
423 if let Err(error) = replace_file(&self.view_path_of(print_id), &bytes) {
424 eprintln!(
425 "printobserver: print {print_id}: its camera view could not be recorded, so a later check reads the one before: {error}"
426 );
427 }
428 }
429
430 fn decide(&self, print_id: PrintId, verdict: &PrintAlignment) {
434 let Ok(bytes) = printobserver_types::serde_json::to_vec(verdict) else {
435 return;
436 };
437 match replace_file(&self.path_of(print_id), &bytes) {
438 Ok(()) => eprintln!(
439 "printobserver: print {print_id}: first-layer alignment {}",
440 said(verdict)
441 ),
442 Err(error) => eprintln!(
443 "printobserver: print {print_id}: first-layer alignment {} could not be recorded: {error}",
444 said(verdict)
445 ),
446 }
447 }
448
449 #[must_use]
454 pub fn correction_in_force(&self, print_id: PrintId) -> Option<ViewCorrection> {
455 let calibration = self.calibration.as_deref()?;
456 let PrintAlignment::Passed { correction_px, .. } = self.print_alignment(print_id) else {
457 return None;
458 };
459 Some(self.view_state(print_id).correction.unwrap_or_else(|| {
460 ViewCorrection::translation(
461 correction_px,
462 calibration
463 .landmarks
464 .iter()
465 .map(|landmark| ReferenceLandmark {
466 name: landmark.name.clone(),
467 offset_px: [0.0, 0.0],
468 score: 1.0,
469 })
470 .collect(),
471 )
472 }))
473 }
474
475 #[must_use]
478 pub fn inconclusive(&self, print_id: PrintId) -> Option<InconclusiveReason> {
479 self.view_state(print_id).inconclusive
480 }
481
482 #[must_use]
485 pub fn last_check_image(&self, print_id: PrintId) -> Option<LastCheckImage> {
486 self.view_state(print_id).last_check_image
487 }
488
489 #[must_use]
493 pub fn note_check_image(
494 &self,
495 print_id: PrintId,
496 shown: LastCheckImage,
497 frame_sha256: &str,
498 ) -> Option<EventBody> {
499 let mut state = self.view_state(print_id);
500 let code = |image: &LastCheckImage| image.fallback.as_ref().map(|fallback| fallback.code);
501 let changed = state
502 .last_check_image
503 .as_ref()
504 .is_none_or(|last| last.kind != shown.kind || code(last) != code(&shown));
505 let notice = changed.then(|| {
506 body_of(&crate::judgements::CheckImageChangedPayload {
507 kind: shown.kind,
508 fallback: shown.fallback.clone(),
509 frame_sha256: frame_sha256.to_owned(),
510 })
511 });
512 state.last_check_image = Some(shown);
513 self.keep_view_state(print_id, &state);
514 notice.flatten()
515 }
516
517 #[must_use]
532 pub fn judge(&self, print_id: PrintId, judging: &Judging<'_>) -> Judged {
533 let Some(calibration) = self.calibration.as_deref() else {
534 return Judged::unjudged(PrintAlignment::Unavailable);
535 };
536 let mut judged = Judged::unjudged(self.print_alignment(print_id));
537 let mut state = self.view_state(print_id);
538 let in_force = self.correction_in_force(print_id);
539 let sha = judging.frame_sha256;
540 let landmarks = match landmarks_in_frame(
541 calibration,
542 judging.frame_jpeg,
543 judging.camera_snapshot_url,
544 ) {
545 Ok(landmarks) => landmarks,
546 Err(error @ ComposeError::FrameMismatch { .. }) => {
547 let reason = error.to_string();
548 judged
549 .records
550 .extend(body_of(&crate::judgements::CameraViewJudgedPayload {
551 frame_sha256: sha.to_owned(),
552 outcome: ViewOutcome::FrameMismatch,
553 view_correction: in_force.clone(),
554 reason: Some(reason.clone()),
555 }));
556 if Self::alignment_due(&judged.alignment, judging).is_some() {
557 let failure = failure_of(&error, calibration);
558 judged.records.extend(body_of(
559 &crate::judgements::FirstLayerAlignmentJudgedPayload {
560 verdict: crate::judgements::AlignmentJudgedVerdict::Failed,
561 offset_px: None,
562 correction_px: None,
563 match_strength: None,
564 reason: failure_sentence(&failure),
565 frame_sha256: sha.to_owned(),
566 view_correction: in_force.clone(),
567 },
568 ));
569 judged.alignment = PrintAlignment::Failed { reason: failure };
570 self.decide(print_id, &judged.alignment);
571 state.correction = None;
572 state.inconclusive = None;
573 self.keep_view_state(print_id, &state);
574 }
575 judged.correction = in_force.filter(|_| judged.alignment.passed());
576 judged.mismatch = Some(reason);
577 return judged;
578 }
579 Err(error) => {
580 judged.unreadable = Some(error.to_string());
581 return judged;
582 }
583 };
584 if judging.alignment != AlignmentJudging::Never
587 && judged.alignment == PrintAlignment::Pending
588 && judging
589 .plan
590 .is_some_and(|plan| plan.index.first_object_layer().is_none())
591 {
592 judged.alignment = PrintAlignment::Unavailable;
593 self.decide(print_id, &judged.alignment);
594 }
595 let due = Self::alignment_due(&judged.alignment, judging);
596 let view = match (due, &judged.alignment) {
597 (None, PrintAlignment::Passed { .. }) => {
598 let view = judge_found(calibration, landmarks, in_force.as_ref());
599 if view.outcome == ViewOutcome::ViewRefitRejected {
600 judged.alignment = PrintAlignment::Pending;
601 self.decide(print_id, &judged.alignment);
602 state.correction = None;
603 state.inconclusive = None;
604 self.keep_view_state(print_id, &state);
605 judged.rejected.clone_from(&view.reason);
606 } else {
607 judged.correction.clone_from(&in_force);
608 }
609 judged
610 .records
611 .extend(view_record(sha, &view, in_force.clone()));
612 view
613 }
614 (Some(first), _) => self.judge_alignment(
615 print_id,
616 calibration,
617 landmarks,
618 &first,
619 judging,
620 in_force,
621 &mut state,
622 &mut judged,
623 ),
624 (None, _) => {
625 let view = judge_found(calibration, landmarks, None);
626 judged.records.extend(view_record(sha, &view, None));
627 view
628 }
629 };
630 judged.inconclusive = state.inconclusive;
631 judged.view = Some((view.outcome, view.reason));
632 judged
633 }
634
635 #[expect(
638 clippy::too_many_arguments,
639 reason = "the one judgement's inputs and the two records it updates"
640 )]
641 fn judge_alignment(
642 &self,
643 print_id: PrintId,
644 calibration: &CameraCalibration,
645 landmarks: Vec<printobserver_panels::FoundLandmark>,
646 first: &DueAlignment,
647 judging: &Judging<'_>,
648 in_force: Option<ViewCorrection>,
649 state: &mut CameraViewState,
650 judged: &mut Judged,
651 ) -> ViewJudgement {
652 let sha = judging.frame_sha256;
653 let uncorrected = judge_found(calibration, landmarks.clone(), None);
654 let judgement = judge_first_layer(&FirstLayerInputs {
655 alignment: AlignmentInputs {
656 frame_jpeg: judging.frame_jpeg,
657 camera_snapshot_url: judging.camera_snapshot_url,
658 first_layer: &first.first_layer,
659 print_z_mm: first.print_z_mm,
660 calibration,
661 },
662 nozzle_xy_mm: first.nozzle_xy_mm,
663 });
664 let Ok(judgement) = judgement else {
665 judged.records.extend(view_record(sha, &uncorrected, None));
669 return uncorrected;
670 };
671 let found = judgement.found;
672 let (verdict, correction_px, reason) = match judgement.verdict {
673 FirstLayerVerdict::Passed => (
674 crate::judgements::AlignmentJudgedVerdict::Passed,
675 found.map(|found| {
676 printobserver_panels::alignment::correction_shift(
677 &found,
678 &first.first_layer,
679 first.print_z_mm,
680 )
681 }),
682 "clearly_found".to_owned(),
683 ),
684 FirstLayerVerdict::Inconclusive(why) => (
685 crate::judgements::AlignmentJudgedVerdict::Inconclusive,
686 None,
687 why.as_str().to_owned(),
688 ),
689 };
690 judged.records.extend(body_of(
691 &crate::judgements::FirstLayerAlignmentJudgedPayload {
692 verdict,
693 offset_px: found.map(|found| found.offset_px),
694 correction_px,
695 match_strength: found.map(|found| found.match_strength),
696 reason,
697 frame_sha256: sha.to_owned(),
698 view_correction: in_force,
699 },
700 ));
701 match (judgement.verdict, found) {
702 (FirstLayerVerdict::Passed, Some(found)) => {
703 let shift = printobserver_panels::alignment::correction_shift(
704 &found,
705 &first.first_layer,
706 first.print_z_mm,
707 );
708 eprintln!(
709 "printobserver: print {print_id}: the first layer was found shifted [{:.0}, {:.0}] px at Z {:.2}, at a contrast of {:.1}; corrected by [{:.0}, {:.0}] px",
710 found.shift_px[0],
711 found.shift_px[1],
712 first.print_z_mm,
713 found.match_strength,
714 shift[0],
715 shift[1]
716 );
717 let correction = ViewCorrection::translation(shift, uncorrected.agreeing());
718 judged.alignment = PrintAlignment::Passed {
719 offset_px: found.offset_px,
720 correction_px: shift,
721 };
722 self.decide(print_id, &judged.alignment);
723 state.correction = Some(correction.clone());
724 state.inconclusive = None;
725 self.keep_view_state(print_id, state);
726 if uncorrected.moved(calibration) {
727 judged
728 .records
729 .extend(body_of(&crate::judgements::CameraViewRefitPayload {
730 frame_sha256: sha.to_owned(),
731 view_correction: correction.clone(),
732 }));
733 }
734 let view = judge_found(calibration, landmarks, Some(&correction));
735 judged
736 .records
737 .extend(view_record(sha, &view, Some(correction.clone())));
738 judged.correction = Some(correction);
739 view
740 }
741 (FirstLayerVerdict::Inconclusive(why), _) => {
742 judged.alignment = PrintAlignment::Pending;
745 self.decide(print_id, &judged.alignment);
746 state.correction = None;
747 state.inconclusive = Some(why);
748 self.keep_view_state(print_id, state);
749 judged.records.extend(view_record(sha, &uncorrected, None));
750 uncorrected
751 }
752 (FirstLayerVerdict::Passed, None) => {
753 judged.records.extend(view_record(sha, &uncorrected, None));
754 uncorrected
755 }
756 }
757 }
758
759 fn alignment_due(alignment: &PrintAlignment, judging: &Judging<'_>) -> Option<DueAlignment> {
762 let asked = match judging.alignment {
763 AlignmentJudging::Never => false,
764 AlignmentJudging::WhilePending => *alignment == PrintAlignment::Pending,
765 AlignmentJudging::Afresh => true,
766 };
767 if !asked {
768 return None;
769 }
770 let plan = judging.plan?;
771 let index = &plan.index;
772 let position = plan.file_position_bytes;
773 let (first, ends) = index.first_object_layer()?;
774 if position <= ends {
775 return None;
776 }
777 Some(DueAlignment {
778 first_layer: index.layer_toolpath(first).ok()?,
779 print_z_mm: index
780 .layer_at(position)
781 .and_then(|layer| index.layer_z_mm(layer))?,
782 nozzle_xy_mm: index.planned_head_at(position).ok().flatten(),
783 })
784 }
785
786 pub async fn sweep(&self) {
802 let Ok(open) = self.prints.open_prints().await else {
803 return;
804 };
805 let open: Vec<String> = open
806 .iter()
807 .flat_map(|print| {
808 [
809 format!("{}.json", print.id),
810 format!("{}.json.part", print.id),
811 ]
812 })
813 .collect();
814 for directory in [
815 &self.directory,
816 &self.previous_directory,
817 &self.checked_directory,
818 &self.view_directory,
819 ] {
820 let Ok(entries) = std::fs::read_dir(directory) else {
821 continue;
822 };
823 for entry in entries.flatten() {
824 let name = entry.file_name();
825 if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
826 let _ = std::fs::remove_file(entry.path());
827 }
828 }
829 }
830 }
831}
832
833fn reference_in(kept: &[CheckedFrame], print_z_mm: f64, rise_mm: f64) -> Option<&CheckedFrame> {
836 kept.iter()
837 .rev()
838 .find(|checked| checked.print_z_mm <= print_z_mm - rise_mm)
839}
840
841fn kept_with(
846 mut kept: Vec<CheckedFrame>,
847 checked: CheckedFrame,
848 rise_mm: f64,
849) -> Vec<CheckedFrame> {
850 if kept
851 .last()
852 .is_some_and(|last| checked.print_z_mm < last.print_z_mm)
853 {
854 kept.clear();
855 }
856 if let Some(reference) = kept
857 .iter()
858 .rposition(|earlier| earlier.print_z_mm <= checked.print_z_mm - rise_mm)
859 {
860 kept.drain(..reference);
861 }
862 kept.push(checked);
863 if kept.len() > MAX_CHECKED_FRAMES {
864 kept.drain(..kept.len() - MAX_CHECKED_FRAMES);
865 }
866 kept
867}
868
869const REPLACE_ATTEMPTS: u32 = 20;
873const REPLACE_PAUSE: Duration = Duration::from_millis(25);
874
875fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
888 let held = path.with_extension("json.part");
889 attempt_while_refused(
890 || {
891 std::fs::write(&held, bytes)?;
892 std::fs::rename(&held, path)
893 },
894 refused_for_a_moment,
895 REPLACE_ATTEMPTS,
896 REPLACE_PAUSE,
897 )
898 .inspect_err(|_| {
899 let _ = std::fs::remove_file(&held);
900 })
901}
902
903fn attempt_while_refused(
906 mut attempt: impl FnMut() -> std::io::Result<()>,
907 refused: impl Fn(&std::io::Error) -> bool,
908 attempts: u32,
909 pause: Duration,
910) -> std::io::Result<()> {
911 let mut made = 1;
912 loop {
913 match attempt() {
914 Err(error) if made < attempts && refused(&error) => {
915 std::thread::sleep(pause);
916 made += 1;
917 }
918 answered => return answered,
919 }
920 }
921}
922
923#[cfg(windows)]
926fn refused_for_a_moment(error: &std::io::Error) -> bool {
927 matches!(error.raw_os_error(), Some(5 | 32))
928}
929
930#[cfg(not(windows))]
933fn refused_for_a_moment(_error: &std::io::Error) -> bool {
934 false
935}
936
937fn size_of(text: &str) -> [u32; 2] {
939 let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
940 [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
941}
942
943fn said(verdict: &PrintAlignment) -> String {
945 match verdict {
946 PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
947 PrintAlignment::Pending => "pending".to_owned(),
948 PrintAlignment::Passed {
949 offset_px,
950 correction_px,
951 } => format!(
952 "passed, offset {offset_px:.1} px, corrected by [{:.0}, {:.0}] px",
953 correction_px[0], correction_px[1]
954 ),
955 PrintAlignment::Failed {
956 reason: AlignmentFailure::Offset { offset_px },
957 } => format!("failed, offset {offset_px:.1} px"),
958 PrintAlignment::Failed {
959 reason: AlignmentFailure::Resolution { expected, got },
960 } => format!(
961 "failed: the camera's frames are {}x{}, the calibration's {}x{}",
962 got[0], got[1], expected[0], expected[1]
963 ),
964 PrintAlignment::Failed {
965 reason: AlignmentFailure::Stream,
966 } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
967 }
968}
969
970#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
972#[serde(crate = "printobserver_types::serde")]
973struct CameraViewState {
974 #[serde(default)]
976 correction: Option<ViewCorrection>,
977 #[serde(default)]
980 inconclusive: Option<InconclusiveReason>,
981 #[serde(default)]
983 last_check_image: Option<LastCheckImage>,
984}
985
986#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
988#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
989#[schemars(crate = "printobserver_types::schemars")]
990pub struct LastCheckImage {
991 pub at: Timestamp,
993 pub kind: ImageKind,
995 pub fallback: Option<ImageFallback>,
997}
998
999impl Sample for LastCheckImage {
1000 fn sample_full() -> Self {
1001 Self {
1002 at: Timestamp::sample_full(),
1003 kind: ImageKind::WholeFrame,
1004 fallback: Some(ImageFallback::sample_full()),
1005 }
1006 }
1007
1008 fn sample_minimal() -> Self {
1009 Self {
1010 at: Timestamp::sample_full(),
1011 kind: ImageKind::ThreePanel,
1012 fallback: None,
1013 }
1014 }
1015}
1016
1017#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1019pub enum AlignmentJudging {
1020 Never,
1022 WhilePending,
1024 Afresh,
1027}
1028
1029#[derive(Debug, Clone, Copy)]
1031pub struct Judging<'a> {
1032 pub frame_jpeg: &'a [u8],
1034 pub frame_sha256: &'a str,
1036 pub camera_snapshot_url: &'a str,
1038 pub plan: Option<&'a PlanPosition>,
1040 pub alignment: AlignmentJudging,
1042}
1043
1044#[derive(Debug, Clone, PartialEq)]
1046pub struct Judged {
1047 pub records: Vec<EventBody>,
1049 pub alignment: PrintAlignment,
1051 pub correction: Option<ViewCorrection>,
1054 pub view: Option<(ViewOutcome, Option<String>)>,
1057 pub rejected: Option<String>,
1060 pub mismatch: Option<String>,
1062 pub unreadable: Option<String>,
1064 pub inconclusive: Option<InconclusiveReason>,
1067}
1068
1069impl Judged {
1070 #[must_use]
1074 pub fn nothing_to_judge(alignment: PrintAlignment, kept_with: Option<EventBody>) -> Self {
1075 Self {
1076 records: kept_with.into_iter().collect(),
1077 ..Self::unjudged(alignment)
1078 }
1079 }
1080
1081 const fn unjudged(alignment: PrintAlignment) -> Self {
1083 Self {
1084 records: Vec::new(),
1085 alignment,
1086 correction: None,
1087 view: None,
1088 rejected: None,
1089 mismatch: None,
1090 unreadable: None,
1091 inconclusive: None,
1092 }
1093 }
1094}
1095
1096impl PrintAlignment {
1097 #[must_use]
1099 pub const fn passed(&self) -> bool {
1100 matches!(self, Self::Passed { .. })
1101 }
1102}
1103
1104struct DueAlignment {
1106 first_layer: printobserver_core::LayerToolpath,
1108 print_z_mm: f64,
1110 nozzle_xy_mm: Option<[f64; 2]>,
1112}
1113
1114fn body_of<P: EventPayload>(payload: &P) -> Option<EventBody> {
1117 EventBody::of(payload).ok()
1118}
1119
1120fn view_record(
1124 frame_sha256: &str,
1125 view: &ViewJudgement,
1126 view_correction: Option<ViewCorrection>,
1127) -> Option<EventBody> {
1128 let reason = if view.outcome == ViewOutcome::Refit {
1129 Some(crate::check_images::CALIBRATION_STALE.to_owned())
1130 } else {
1131 view.reason.clone()
1132 };
1133 body_of(&crate::judgements::CameraViewJudgedPayload {
1134 frame_sha256: frame_sha256.to_owned(),
1135 outcome: view.outcome,
1136 view_correction,
1137 reason,
1138 })
1139}
1140
1141fn failure_of(error: &ComposeError, calibration: &CameraCalibration) -> AlignmentFailure {
1143 match error {
1144 ComposeError::FrameMismatch {
1145 field: FrameField::Resolution,
1146 got,
1147 ..
1148 } => AlignmentFailure::Resolution {
1149 expected: calibration.image_size_px,
1150 got: size_of(got),
1151 },
1152 _ => AlignmentFailure::Stream,
1153 }
1154}
1155
1156#[must_use]
1158pub fn failure_sentence(failure: &AlignmentFailure) -> String {
1159 match failure {
1160 AlignmentFailure::Offset { offset_px } => format!(
1161 "the printed first layer lies {offset_px:.1} px from where the calibration projects it"
1162 ),
1163 AlignmentFailure::Resolution { expected, got } => format!(
1164 "the camera's frames are {}x{} and the calibration's {}x{}",
1165 got[0], got[1], expected[0], expected[1]
1166 ),
1167 AlignmentFailure::Stream => {
1168 "the camera is not the stream the calibration was fitted on".to_owned()
1169 }
1170 }
1171}
1172
1173#[cfg(test)]
1174mod tests {
1175 use super::{CheckedFrame, MAX_CHECKED_FRAMES, attempt_while_refused, kept_with, reference_in};
1176 use std::cell::Cell;
1177 use std::io::{Error, ErrorKind};
1178 use std::time::Duration;
1179
1180 fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
1183 move || {
1184 made.set(made.get() + 1);
1185 if made.get() <= refusals {
1186 Err(Error::from(ErrorKind::PermissionDenied))
1187 } else {
1188 Ok(())
1189 }
1190 }
1191 }
1192
1193 #[test]
1194 fn a_momentary_refusal_is_attempted_again_until_it_passes() {
1195 let made = Cell::new(0);
1196 let answered =
1197 attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
1198 assert!(answered.is_ok(), "{answered:?}");
1199 assert_eq!(made.get(), 3);
1200 }
1201
1202 #[test]
1203 fn a_refusal_that_outlasts_every_attempt_is_answered() {
1204 let made = Cell::new(0);
1205 let answered =
1206 attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
1207 assert_eq!(
1208 answered.map_err(|error| error.kind()),
1209 Err(ErrorKind::PermissionDenied)
1210 );
1211 assert_eq!(made.get(), 4);
1212 }
1213
1214 #[test]
1215 fn a_refusal_that_is_not_momentary_is_answered_at_once() {
1216 let made = Cell::new(0);
1217 let answered =
1218 attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
1219 assert!(answered.is_err());
1220 assert_eq!(made.get(), 1);
1221 }
1222
1223 #[cfg(windows)]
1227 #[test]
1228 fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
1229 use std::os::windows::fs::OpenOptionsExt;
1230 let directory = tempfile::TempDir::new().expect("a directory");
1231 let path = directory.path().join("record.json");
1232 std::fs::write(&path, b"before").expect("a record");
1233 let held = std::fs::OpenOptions::new()
1234 .read(true)
1235 .share_mode(0)
1236 .open(&path)
1237 .expect("the record held");
1238 let release = std::thread::spawn(move || {
1239 std::thread::sleep(Duration::from_millis(150));
1240 drop(held);
1241 });
1242 super::replace_file(&path, b"after").expect("the record replaced");
1243 release.join().expect("the handle let go");
1244 assert_eq!(std::fs::read(&path).expect("the record"), b"after");
1245 assert!(!path.with_extension("json.part").exists());
1246 }
1247
1248 #[cfg(windows)]
1249 #[test]
1250 fn only_a_held_file_is_a_momentary_refusal_on_windows() {
1251 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
1252 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
1253 assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
1254 }
1255
1256 fn at(second: i64, z: f64) -> CheckedFrame {
1258 CheckedFrame {
1259 frame: format!("frame-{second}.jpg").into(),
1260 captured_at: printobserver_types::Timestamp::from_unix_seconds(1_791_489_600 + second)
1261 .expect("a time"),
1262 print_z_mm: z,
1263 }
1264 }
1265
1266 fn heights(kept: &[CheckedFrame]) -> Vec<f64> {
1268 kept.iter().map(|checked| checked.print_z_mm).collect()
1269 }
1270
1271 #[test]
1275 fn after_a_planned_change_growth_is_measured_from_frames_after_it() {
1276 let state = tempfile::TempDir::new().expect("a state directory");
1277 let store =
1278 printobserver_store_sqlite::MemoryStore::new(state.path()).expect("an in-memory store");
1279 let alignments = super::Alignments::new(state.path(), None, std::sync::Arc::new(store))
1280 .expect("the verdicts' directories");
1281 let print_id = printobserver_types::PrintId::new();
1282 for (second, z) in [(0, 0.2), (60, 0.6)] {
1283 alignments.record_checked_frame(print_id, at(second, z), 0.4);
1284 }
1285 let before = alignments.growth_reference(print_id, 1.0, 0.4);
1286 assert_eq!(before.map(|checked| checked.print_z_mm), Some(0.6));
1287
1288 alignments.restart_growth(print_id);
1289 assert_eq!(alignments.growth_reference(print_id, 1.0, 0.4), None);
1290 alignments.record_checked_frame(print_id, at(3_000, 0.8), 0.4);
1291 alignments.record_checked_frame(print_id, at(3_120, 1.4), 0.4);
1292 let after = alignments.growth_reference(print_id, 1.4, 0.4);
1293 assert_eq!(
1294 after.map(|checked| checked.captured_at),
1295 Some(at(3_000, 0.8).captured_at)
1296 );
1297 alignments.restart_growth(print_id);
1299 alignments.restart_growth(print_id);
1300 assert!(alignments.checked_frames(print_id).is_empty());
1301 }
1302
1303 #[test]
1304 fn a_check_measures_from_the_newest_frame_far_enough_below_it() {
1305 let kept = [at(0, 0.2), at(60, 0.8), at(120, 2.0), at(180, 2.6)];
1306 assert_eq!(
1307 reference_in(&kept, 5.8, 3.0).map(|checked| checked.print_z_mm),
1308 Some(2.6)
1309 );
1310 assert_eq!(
1311 reference_in(&kept, 3.5, 3.0).map(|checked| checked.print_z_mm),
1312 Some(0.2)
1313 );
1314 assert_eq!(reference_in(&kept, 3.1, 3.0), None, "none is 3 mm below");
1315 }
1316
1317 #[test]
1318 fn only_what_a_later_check_can_measure_from_is_kept() {
1319 let mut kept = Vec::new();
1320 for (second, z) in [(0, 0.2), (60, 0.8), (120, 2.0), (180, 3.4), (240, 4.0)] {
1321 kept = kept_with(kept, at(second, z), 3.0);
1322 }
1323 assert_eq!(
1324 heights(&kept),
1325 [0.8, 2.0, 3.4, 4.0],
1326 "0.2 is below 0.8, which is itself 3 mm below 4.0, so no later check needs it"
1327 );
1328 assert_eq!(
1329 heights(&kept_with(kept, at(300, 1.0), 3.0)),
1330 [1.0],
1331 "a plan gone back down starts the record again"
1332 );
1333 }
1334
1335 #[test]
1336 fn the_oldest_checked_frames_go_past_the_most_kept() {
1337 let mut kept = Vec::new();
1338 for second in 0..=i64::try_from(MAX_CHECKED_FRAMES).expect("a count") {
1339 kept = kept_with(kept, at(second, 5.0), 3.0);
1340 }
1341 assert_eq!(kept.len(), MAX_CHECKED_FRAMES);
1342 assert_eq!(kept[0].captured_at, at(1, 5.0).captured_at);
1343 }
1344}