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]
455 pub fn correction_in_force(&self, print_id: PrintId) -> Option<ViewCorrection> {
456 let calibration = self.calibration.as_deref()?;
457 if let Some(checked) = self.view_state(print_id).camera_check {
458 return Some(checked.correction);
459 }
460 let PrintAlignment::Passed { correction_px, .. } = self.print_alignment(print_id) else {
461 return None;
462 };
463 Some(self.view_state(print_id).correction.unwrap_or_else(|| {
464 ViewCorrection::translation(
465 correction_px,
466 calibration
467 .landmarks
468 .iter()
469 .map(|landmark| ReferenceLandmark {
470 name: landmark.name.clone(),
471 offset_px: [0.0, 0.0],
472 score: 1.0,
473 })
474 .collect(),
475 )
476 }))
477 }
478
479 pub fn adopt_camera_check(&self, print_id: PrintId, record: &printobserver_types::EventRecord) {
485 let mut state = self.view_state(print_id);
486 let Some(Ok(payload)) = record.payload_as::<crate::camera_check::CameraCheckedPayload>()
487 else {
488 return;
489 };
490 let check = payload.camera_check;
491 if state
492 .camera_check
493 .as_ref()
494 .is_some_and(|kept| kept.id == check.id)
495 {
496 return;
497 }
498 let (printobserver_core::CameraCheckVerdict::Aligned, Some(correction)) =
499 (check.verdict, check.correction)
500 else {
501 return;
502 };
503 eprintln!(
504 "printobserver: print {print_id}: drawn through camera check {} from its first check, corrected by [{:.1}, {:.1}] px",
505 check.id,
506 correction.shift_px()[0],
507 correction.shift_px()[1]
508 );
509 state.camera_check = Some(CheckedCamera {
510 id: check.id,
511 correction,
512 });
513 self.keep_view_state(print_id, &state);
514 }
515
516 #[must_use]
518 pub fn started_under_a_camera_check(&self, print_id: PrintId) -> bool {
519 self.view_state(print_id).camera_check.is_some()
520 }
521
522 #[must_use]
525 pub fn inconclusive(&self, print_id: PrintId) -> Option<InconclusiveReason> {
526 self.view_state(print_id).inconclusive
527 }
528
529 #[must_use]
532 pub fn last_check_image(&self, print_id: PrintId) -> Option<LastCheckImage> {
533 self.view_state(print_id).last_check_image
534 }
535
536 #[must_use]
540 pub fn note_check_image(
541 &self,
542 print_id: PrintId,
543 shown: LastCheckImage,
544 frame_sha256: &str,
545 ) -> Option<EventBody> {
546 let mut state = self.view_state(print_id);
547 let code = |image: &LastCheckImage| image.fallback.as_ref().map(|fallback| fallback.code);
548 let changed = state
549 .last_check_image
550 .as_ref()
551 .is_none_or(|last| last.kind != shown.kind || code(last) != code(&shown));
552 let notice = changed.then(|| {
553 body_of(&crate::judgements::CheckImageChangedPayload {
554 kind: shown.kind,
555 fallback: shown.fallback.clone(),
556 frame_sha256: frame_sha256.to_owned(),
557 })
558 });
559 state.last_check_image = Some(shown);
560 self.keep_view_state(print_id, &state);
561 notice.flatten()
562 }
563
564 #[must_use]
579 pub fn judge(&self, print_id: PrintId, judging: &Judging<'_>) -> Judged {
580 let Some(calibration) = self.calibration.as_deref() else {
581 return Judged::unjudged(PrintAlignment::Unavailable);
582 };
583 let mut judged = Judged::unjudged(self.print_alignment(print_id));
584 let mut state = self.view_state(print_id);
585 let in_force = self.correction_in_force(print_id);
586 let sha = judging.frame_sha256;
587 let landmarks = match landmarks_in_frame(
588 calibration,
589 judging.frame_jpeg,
590 judging.camera_snapshot_url,
591 ) {
592 Ok(landmarks) => landmarks,
593 Err(error @ ComposeError::FrameMismatch { .. }) => {
594 return self.mismatched(print_id, calibration, &error, judging, in_force, judged);
595 }
596 Err(error) => {
597 judged.unreadable = Some(error.to_string());
598 return judged;
599 }
600 };
601 if judging.alignment != AlignmentJudging::Never
604 && judged.alignment == PrintAlignment::Pending
605 && judging
606 .plan
607 .is_some_and(|plan| plan.index.first_object_layer().is_none())
608 {
609 judged.alignment = PrintAlignment::Unavailable;
610 self.decide(print_id, &judged.alignment);
611 }
612 if let Some(checked) = state.camera_check.clone() {
613 return self.judge_under_check(
614 print_id,
615 calibration,
616 landmarks,
617 judging,
618 &checked,
619 &mut state,
620 judged,
621 );
622 }
623 let due = Self::alignment_due(&judged.alignment, judging);
624 let view = match (due, &judged.alignment) {
625 (None, PrintAlignment::Passed { .. }) => {
626 let view = judge_found(calibration, landmarks, in_force.as_ref());
627 if view.outcome == ViewOutcome::ViewRefitRejected {
628 judged.alignment = PrintAlignment::Pending;
629 self.decide(print_id, &judged.alignment);
630 state.correction = None;
631 state.inconclusive = None;
632 self.keep_view_state(print_id, &state);
633 judged.rejected.clone_from(&view.reason);
634 } else {
635 judged.correction.clone_from(&in_force);
636 }
637 judged
638 .records
639 .extend(view_record(sha, &view, in_force.clone()));
640 view
641 }
642 (Some(first), _) => self.judge_alignment(
643 print_id,
644 calibration,
645 landmarks,
646 &first,
647 judging,
648 in_force,
649 &mut state,
650 &mut judged,
651 ),
652 (None, _) => {
653 let view = judge_found(calibration, landmarks, None);
654 judged.records.extend(view_record(sha, &view, None));
655 view
656 }
657 };
658 judged.inconclusive = state.inconclusive;
659 judged.view = Some((view.outcome, view.reason));
660 judged
661 }
662
663 fn mismatched(
667 &self,
668 print_id: PrintId,
669 calibration: &CameraCalibration,
670 error: &ComposeError,
671 judging: &Judging<'_>,
672 in_force: Option<ViewCorrection>,
673 mut judged: Judged,
674 ) -> Judged {
675 let sha = judging.frame_sha256;
676 let reason = error.to_string();
677 judged
678 .records
679 .extend(body_of(&crate::judgements::CameraViewJudgedPayload {
680 frame_sha256: sha.to_owned(),
681 outcome: ViewOutcome::FrameMismatch,
682 view_correction: in_force.clone(),
683 reason: Some(reason.clone()),
684 }));
685 if Self::alignment_due(&judged.alignment, judging).is_some() {
686 let failure = failure_of(error, calibration);
687 judged.records.extend(body_of(
688 &crate::judgements::FirstLayerAlignmentJudgedPayload {
689 verdict: crate::judgements::AlignmentJudgedVerdict::Failed,
690 offset_px: None,
691 correction_px: None,
692 match_strength: None,
693 reason: failure_sentence(&failure),
694 frame_sha256: sha.to_owned(),
695 view_correction: in_force.clone(),
696 },
697 ));
698 judged.alignment = PrintAlignment::Failed { reason: failure };
699 self.decide(print_id, &judged.alignment);
700 let mut state = self.view_state(print_id);
701 state.correction = None;
702 state.inconclusive = None;
703 self.keep_view_state(print_id, &state);
704 }
705 judged.correction = in_force.filter(|_| judged.alignment.passed());
706 judged.mismatch = Some(reason);
707 judged
708 }
709
710 #[expect(
719 clippy::too_many_arguments,
720 reason = "the one judgement's inputs and the two records it updates"
721 )]
722 fn judge_under_check(
723 &self,
724 print_id: PrintId,
725 calibration: &CameraCalibration,
726 landmarks: Vec<printobserver_panels::FoundLandmark>,
727 judging: &Judging<'_>,
728 checked: &CheckedCamera,
729 state: &mut CameraViewState,
730 mut judged: Judged,
731 ) -> Judged {
732 let sha = judging.frame_sha256;
733 if let Some(first) = Self::alignment_due(&judged.alignment, judging) {
734 self.record_first_layer(
735 print_id,
736 calibration,
737 &first,
738 judging,
739 checked,
740 state,
741 &mut judged,
742 );
743 }
744 let view = judge_found(calibration, landmarks, Some(&checked.correction));
745 if view.outcome == ViewOutcome::ViewRefitRejected {
746 judged.rejected.clone_from(&view.reason);
747 } else if view.outcome.drawable() {
748 judged.correction = Some(checked.correction.clone());
749 }
750 judged
751 .records
752 .extend(body_of(&crate::judgements::CameraViewJudgedPayload {
753 frame_sha256: sha.to_owned(),
754 outcome: view.outcome,
755 view_correction: Some(checked.correction.clone()),
756 reason: view.reason.clone(),
757 }));
758 judged.camera_check = Some(checked.id);
759 judged.inconclusive = state.inconclusive;
760 judged.view = Some((view.outcome, view.reason));
761 judged
762 }
763
764 #[expect(
768 clippy::too_many_arguments,
769 reason = "the one judgement's inputs and the two records it updates"
770 )]
771 fn record_first_layer(
772 &self,
773 print_id: PrintId,
774 calibration: &CameraCalibration,
775 first: &DueAlignment,
776 judging: &Judging<'_>,
777 checked: &CheckedCamera,
778 state: &mut CameraViewState,
779 judged: &mut Judged,
780 ) {
781 let Ok(judgement) = judge_first_layer(&FirstLayerInputs {
782 alignment: AlignmentInputs {
783 frame_jpeg: judging.frame_jpeg,
784 camera_snapshot_url: judging.camera_snapshot_url,
785 first_layer: &first.first_layer,
786 print_z_mm: first.print_z_mm,
787 calibration,
788 },
789 nozzle_xy_mm: first.nozzle_xy_mm,
790 }) else {
791 return;
794 };
795 let found = judgement.found;
796 let shift = |found: &printobserver_panels::AlignmentVerdict| {
797 printobserver_panels::alignment::correction_shift(
798 found,
799 &first.first_layer,
800 first.print_z_mm,
801 )
802 };
803 let (verdict, reason) = match judgement.verdict {
804 FirstLayerVerdict::Passed => (
805 crate::judgements::AlignmentJudgedVerdict::Passed,
806 "clearly_found".to_owned(),
807 ),
808 FirstLayerVerdict::Inconclusive(why) => (
809 crate::judgements::AlignmentJudgedVerdict::Inconclusive,
810 why.as_str().to_owned(),
811 ),
812 };
813 judged.records.extend(body_of(
814 &crate::judgements::FirstLayerAlignmentJudgedPayload {
815 verdict,
816 offset_px: found.map(|found| found.offset_px),
817 correction_px: (judgement.verdict == FirstLayerVerdict::Passed)
818 .then(|| found.as_ref().map(shift))
819 .flatten(),
820 match_strength: found.map(|found| found.match_strength),
821 reason,
822 frame_sha256: judging.frame_sha256.to_owned(),
823 view_correction: Some(checked.correction.clone()),
824 },
825 ));
826 match (judgement.verdict, found) {
827 (FirstLayerVerdict::Passed, Some(found)) => {
828 judged.alignment = PrintAlignment::Passed {
829 offset_px: found.offset_px,
830 correction_px: shift(&found),
831 };
832 state.inconclusive = None;
833 }
834 (FirstLayerVerdict::Inconclusive(why), _) => {
835 judged.alignment = PrintAlignment::Pending;
836 state.inconclusive = Some(why);
837 }
838 (FirstLayerVerdict::Passed, None) => return,
839 }
840 self.decide(print_id, &judged.alignment);
841 self.keep_view_state(print_id, state);
842 }
843
844 #[expect(
847 clippy::too_many_arguments,
848 reason = "the one judgement's inputs and the two records it updates"
849 )]
850 fn judge_alignment(
851 &self,
852 print_id: PrintId,
853 calibration: &CameraCalibration,
854 landmarks: Vec<printobserver_panels::FoundLandmark>,
855 first: &DueAlignment,
856 judging: &Judging<'_>,
857 in_force: Option<ViewCorrection>,
858 state: &mut CameraViewState,
859 judged: &mut Judged,
860 ) -> ViewJudgement {
861 let sha = judging.frame_sha256;
862 let uncorrected = judge_found(calibration, landmarks.clone(), None);
863 let judgement = judge_first_layer(&FirstLayerInputs {
864 alignment: AlignmentInputs {
865 frame_jpeg: judging.frame_jpeg,
866 camera_snapshot_url: judging.camera_snapshot_url,
867 first_layer: &first.first_layer,
868 print_z_mm: first.print_z_mm,
869 calibration,
870 },
871 nozzle_xy_mm: first.nozzle_xy_mm,
872 });
873 let Ok(judgement) = judgement else {
874 judged.records.extend(view_record(sha, &uncorrected, None));
878 return uncorrected;
879 };
880 let found = judgement.found;
881 let (verdict, correction_px, reason) = match judgement.verdict {
882 FirstLayerVerdict::Passed => (
883 crate::judgements::AlignmentJudgedVerdict::Passed,
884 found.map(|found| {
885 printobserver_panels::alignment::correction_shift(
886 &found,
887 &first.first_layer,
888 first.print_z_mm,
889 )
890 }),
891 "clearly_found".to_owned(),
892 ),
893 FirstLayerVerdict::Inconclusive(why) => (
894 crate::judgements::AlignmentJudgedVerdict::Inconclusive,
895 None,
896 why.as_str().to_owned(),
897 ),
898 };
899 judged.records.extend(body_of(
900 &crate::judgements::FirstLayerAlignmentJudgedPayload {
901 verdict,
902 offset_px: found.map(|found| found.offset_px),
903 correction_px,
904 match_strength: found.map(|found| found.match_strength),
905 reason,
906 frame_sha256: sha.to_owned(),
907 view_correction: in_force,
908 },
909 ));
910 match (judgement.verdict, found) {
911 (FirstLayerVerdict::Passed, Some(found)) => {
912 let shift = printobserver_panels::alignment::correction_shift(
913 &found,
914 &first.first_layer,
915 first.print_z_mm,
916 );
917 eprintln!(
918 "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",
919 found.shift_px[0],
920 found.shift_px[1],
921 first.print_z_mm,
922 found.match_strength,
923 shift[0],
924 shift[1]
925 );
926 let correction = ViewCorrection::translation(shift, uncorrected.agreeing());
927 judged.alignment = PrintAlignment::Passed {
928 offset_px: found.offset_px,
929 correction_px: shift,
930 };
931 self.decide(print_id, &judged.alignment);
932 state.correction = Some(correction.clone());
933 state.inconclusive = None;
934 self.keep_view_state(print_id, state);
935 if uncorrected.moved(calibration) {
936 judged
937 .records
938 .extend(body_of(&crate::judgements::CameraViewRefitPayload {
939 frame_sha256: sha.to_owned(),
940 view_correction: correction.clone(),
941 }));
942 }
943 let view = judge_found(calibration, landmarks, Some(&correction));
944 judged
945 .records
946 .extend(view_record(sha, &view, Some(correction.clone())));
947 judged.correction = Some(correction);
948 view
949 }
950 (FirstLayerVerdict::Inconclusive(why), _) => {
951 judged.alignment = PrintAlignment::Pending;
954 self.decide(print_id, &judged.alignment);
955 state.correction = None;
956 state.inconclusive = Some(why);
957 self.keep_view_state(print_id, state);
958 judged.records.extend(view_record(sha, &uncorrected, None));
959 uncorrected
960 }
961 (FirstLayerVerdict::Passed, None) => {
962 judged.records.extend(view_record(sha, &uncorrected, None));
963 uncorrected
964 }
965 }
966 }
967
968 fn alignment_due(alignment: &PrintAlignment, judging: &Judging<'_>) -> Option<DueAlignment> {
971 let asked = match judging.alignment {
972 AlignmentJudging::Never => false,
973 AlignmentJudging::WhilePending => *alignment == PrintAlignment::Pending,
974 AlignmentJudging::Afresh => true,
975 };
976 if !asked {
977 return None;
978 }
979 let plan = judging.plan?;
980 let index = &plan.index;
981 let position = plan.file_position_bytes;
982 let (first, ends) = index.first_object_layer()?;
983 if position <= ends {
984 return None;
985 }
986 Some(DueAlignment {
987 first_layer: index.layer_toolpath(first).ok()?,
988 print_z_mm: index
989 .layer_at(position)
990 .and_then(|layer| index.layer_z_mm(layer))?,
991 nozzle_xy_mm: index.planned_head_at(position).ok().flatten(),
992 })
993 }
994
995 pub async fn sweep(&self) {
1011 let Ok(open) = self.prints.open_prints().await else {
1012 return;
1013 };
1014 let open: Vec<String> = open
1015 .iter()
1016 .flat_map(|print| {
1017 [
1018 format!("{}.json", print.id),
1019 format!("{}.json.part", print.id),
1020 ]
1021 })
1022 .collect();
1023 for directory in [
1024 &self.directory,
1025 &self.previous_directory,
1026 &self.checked_directory,
1027 &self.view_directory,
1028 ] {
1029 let Ok(entries) = std::fs::read_dir(directory) else {
1030 continue;
1031 };
1032 for entry in entries.flatten() {
1033 let name = entry.file_name();
1034 if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
1035 let _ = std::fs::remove_file(entry.path());
1036 }
1037 }
1038 }
1039 }
1040}
1041
1042fn reference_in(kept: &[CheckedFrame], print_z_mm: f64, rise_mm: f64) -> Option<&CheckedFrame> {
1045 kept.iter()
1046 .rev()
1047 .find(|checked| checked.print_z_mm <= print_z_mm - rise_mm)
1048}
1049
1050fn kept_with(
1055 mut kept: Vec<CheckedFrame>,
1056 checked: CheckedFrame,
1057 rise_mm: f64,
1058) -> Vec<CheckedFrame> {
1059 if kept
1060 .last()
1061 .is_some_and(|last| checked.print_z_mm < last.print_z_mm)
1062 {
1063 kept.clear();
1064 }
1065 if let Some(reference) = kept
1066 .iter()
1067 .rposition(|earlier| earlier.print_z_mm <= checked.print_z_mm - rise_mm)
1068 {
1069 kept.drain(..reference);
1070 }
1071 kept.push(checked);
1072 if kept.len() > MAX_CHECKED_FRAMES {
1073 kept.drain(..kept.len() - MAX_CHECKED_FRAMES);
1074 }
1075 kept
1076}
1077
1078const REPLACE_ATTEMPTS: u32 = 20;
1082const REPLACE_PAUSE: Duration = Duration::from_millis(25);
1083
1084fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
1097 let held = path.with_extension("json.part");
1098 attempt_while_refused(
1099 || {
1100 std::fs::write(&held, bytes)?;
1101 std::fs::rename(&held, path)
1102 },
1103 refused_for_a_moment,
1104 REPLACE_ATTEMPTS,
1105 REPLACE_PAUSE,
1106 )
1107 .inspect_err(|_| {
1108 let _ = std::fs::remove_file(&held);
1109 })
1110}
1111
1112fn attempt_while_refused(
1115 mut attempt: impl FnMut() -> std::io::Result<()>,
1116 refused: impl Fn(&std::io::Error) -> bool,
1117 attempts: u32,
1118 pause: Duration,
1119) -> std::io::Result<()> {
1120 let mut made = 1;
1121 loop {
1122 match attempt() {
1123 Err(error) if made < attempts && refused(&error) => {
1124 std::thread::sleep(pause);
1125 made += 1;
1126 }
1127 answered => return answered,
1128 }
1129 }
1130}
1131
1132#[cfg(windows)]
1135fn refused_for_a_moment(error: &std::io::Error) -> bool {
1136 matches!(error.raw_os_error(), Some(5 | 32))
1137}
1138
1139#[cfg(not(windows))]
1142fn refused_for_a_moment(_error: &std::io::Error) -> bool {
1143 false
1144}
1145
1146fn size_of(text: &str) -> [u32; 2] {
1148 let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
1149 [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
1150}
1151
1152fn said(verdict: &PrintAlignment) -> String {
1154 match verdict {
1155 PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
1156 PrintAlignment::Pending => "pending".to_owned(),
1157 PrintAlignment::Passed {
1158 offset_px,
1159 correction_px,
1160 } => format!(
1161 "passed, offset {offset_px:.1} px, corrected by [{:.0}, {:.0}] px",
1162 correction_px[0], correction_px[1]
1163 ),
1164 PrintAlignment::Failed {
1165 reason: AlignmentFailure::Offset { offset_px },
1166 } => format!("failed, offset {offset_px:.1} px"),
1167 PrintAlignment::Failed {
1168 reason: AlignmentFailure::Resolution { expected, got },
1169 } => format!(
1170 "failed: the camera's frames are {}x{}, the calibration's {}x{}",
1171 got[0], got[1], expected[0], expected[1]
1172 ),
1173 PrintAlignment::Failed {
1174 reason: AlignmentFailure::Stream,
1175 } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
1176 }
1177}
1178
1179#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1181#[serde(crate = "printobserver_types::serde")]
1182struct CameraViewState {
1183 #[serde(default)]
1185 correction: Option<ViewCorrection>,
1186 #[serde(default)]
1189 inconclusive: Option<InconclusiveReason>,
1190 #[serde(default)]
1192 last_check_image: Option<LastCheckImage>,
1193 #[serde(default)]
1196 camera_check: Option<CheckedCamera>,
1197}
1198
1199#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1201#[serde(crate = "printobserver_types::serde")]
1202struct CheckedCamera {
1203 id: printobserver_core::CameraCheckId,
1205 correction: ViewCorrection,
1207}
1208
1209#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1211#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1212#[schemars(crate = "printobserver_types::schemars")]
1213pub struct LastCheckImage {
1214 pub at: Timestamp,
1216 pub kind: ImageKind,
1218 pub fallback: Option<ImageFallback>,
1220}
1221
1222impl Sample for LastCheckImage {
1223 fn sample_full() -> Self {
1224 Self {
1225 at: Timestamp::sample_full(),
1226 kind: ImageKind::WholeFrame,
1227 fallback: Some(ImageFallback::sample_full()),
1228 }
1229 }
1230
1231 fn sample_minimal() -> Self {
1232 Self {
1233 at: Timestamp::sample_full(),
1234 kind: ImageKind::ThreePanel,
1235 fallback: None,
1236 }
1237 }
1238}
1239
1240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1242pub enum AlignmentJudging {
1243 Never,
1245 WhilePending,
1247 Afresh,
1250}
1251
1252impl AlignmentJudging {
1253 #[must_use]
1257 pub const fn of_recheck(paused: bool) -> Self {
1258 if paused { Self::Never } else { Self::Afresh }
1259 }
1260}
1261
1262#[derive(Debug, Clone, Copy)]
1264pub struct Judging<'a> {
1265 pub frame_jpeg: &'a [u8],
1267 pub frame_sha256: &'a str,
1269 pub camera_snapshot_url: &'a str,
1271 pub plan: Option<&'a PlanPosition>,
1273 pub alignment: AlignmentJudging,
1275}
1276
1277#[derive(Debug, Clone, PartialEq)]
1279pub struct Judged {
1280 pub records: Vec<EventBody>,
1282 pub alignment: PrintAlignment,
1284 pub correction: Option<ViewCorrection>,
1287 pub view: Option<(ViewOutcome, Option<String>)>,
1290 pub rejected: Option<String>,
1293 pub mismatch: Option<String>,
1295 pub unreadable: Option<String>,
1297 pub inconclusive: Option<InconclusiveReason>,
1300 pub camera_check: Option<printobserver_core::CameraCheckId>,
1303}
1304
1305impl Judged {
1306 #[must_use]
1310 pub fn nothing_to_judge(alignment: PrintAlignment, kept_with: Option<EventBody>) -> Self {
1311 Self {
1312 records: kept_with.into_iter().collect(),
1313 ..Self::unjudged(alignment)
1314 }
1315 }
1316
1317 const fn unjudged(alignment: PrintAlignment) -> Self {
1319 Self {
1320 records: Vec::new(),
1321 alignment,
1322 correction: None,
1323 view: None,
1324 rejected: None,
1325 mismatch: None,
1326 unreadable: None,
1327 inconclusive: None,
1328 camera_check: None,
1329 }
1330 }
1331}
1332
1333impl PrintAlignment {
1334 #[must_use]
1336 pub const fn passed(&self) -> bool {
1337 matches!(self, Self::Passed { .. })
1338 }
1339}
1340
1341struct DueAlignment {
1343 first_layer: printobserver_core::LayerToolpath,
1345 print_z_mm: f64,
1347 nozzle_xy_mm: Option<[f64; 2]>,
1349}
1350
1351fn body_of<P: EventPayload>(payload: &P) -> Option<EventBody> {
1354 EventBody::of(payload).ok()
1355}
1356
1357fn view_record(
1361 frame_sha256: &str,
1362 view: &ViewJudgement,
1363 view_correction: Option<ViewCorrection>,
1364) -> Option<EventBody> {
1365 let reason = if view.outcome == ViewOutcome::Refit {
1366 Some(crate::check_images::CALIBRATION_STALE.to_owned())
1367 } else {
1368 view.reason.clone()
1369 };
1370 body_of(&crate::judgements::CameraViewJudgedPayload {
1371 frame_sha256: frame_sha256.to_owned(),
1372 outcome: view.outcome,
1373 view_correction,
1374 reason,
1375 })
1376}
1377
1378fn failure_of(error: &ComposeError, calibration: &CameraCalibration) -> AlignmentFailure {
1380 match error {
1381 ComposeError::FrameMismatch {
1382 field: FrameField::Resolution,
1383 got,
1384 ..
1385 } => AlignmentFailure::Resolution {
1386 expected: calibration.image_size_px,
1387 got: size_of(got),
1388 },
1389 _ => AlignmentFailure::Stream,
1390 }
1391}
1392
1393#[must_use]
1395pub fn failure_sentence(failure: &AlignmentFailure) -> String {
1396 match failure {
1397 AlignmentFailure::Offset { offset_px } => format!(
1398 "the printed first layer lies {offset_px:.1} px from where the calibration projects it"
1399 ),
1400 AlignmentFailure::Resolution { expected, got } => format!(
1401 "the camera's frames are {}x{} and the calibration's {}x{}",
1402 got[0], got[1], expected[0], expected[1]
1403 ),
1404 AlignmentFailure::Stream => {
1405 "the camera is not the stream the calibration was fitted on".to_owned()
1406 }
1407 }
1408}
1409
1410#[cfg(test)]
1411mod tests {
1412 use super::{CheckedFrame, MAX_CHECKED_FRAMES, attempt_while_refused, kept_with, reference_in};
1413 use std::cell::Cell;
1414 use std::io::{Error, ErrorKind};
1415 use std::time::Duration;
1416
1417 fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
1420 move || {
1421 made.set(made.get() + 1);
1422 if made.get() <= refusals {
1423 Err(Error::from(ErrorKind::PermissionDenied))
1424 } else {
1425 Ok(())
1426 }
1427 }
1428 }
1429
1430 #[test]
1431 fn a_momentary_refusal_is_attempted_again_until_it_passes() {
1432 let made = Cell::new(0);
1433 let answered =
1434 attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
1435 assert!(answered.is_ok(), "{answered:?}");
1436 assert_eq!(made.get(), 3);
1437 }
1438
1439 #[test]
1440 fn a_refusal_that_outlasts_every_attempt_is_answered() {
1441 let made = Cell::new(0);
1442 let answered =
1443 attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
1444 assert_eq!(
1445 answered.map_err(|error| error.kind()),
1446 Err(ErrorKind::PermissionDenied)
1447 );
1448 assert_eq!(made.get(), 4);
1449 }
1450
1451 #[test]
1452 fn a_refusal_that_is_not_momentary_is_answered_at_once() {
1453 let made = Cell::new(0);
1454 let answered =
1455 attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
1456 assert!(answered.is_err());
1457 assert_eq!(made.get(), 1);
1458 }
1459
1460 #[cfg(windows)]
1464 #[test]
1465 fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
1466 use std::os::windows::fs::OpenOptionsExt;
1467 let directory = tempfile::TempDir::new().expect("a directory");
1468 let path = directory.path().join("record.json");
1469 std::fs::write(&path, b"before").expect("a record");
1470 let held = std::fs::OpenOptions::new()
1471 .read(true)
1472 .share_mode(0)
1473 .open(&path)
1474 .expect("the record held");
1475 let release = std::thread::spawn(move || {
1476 std::thread::sleep(Duration::from_millis(150));
1477 drop(held);
1478 });
1479 super::replace_file(&path, b"after").expect("the record replaced");
1480 release.join().expect("the handle let go");
1481 assert_eq!(std::fs::read(&path).expect("the record"), b"after");
1482 assert!(!path.with_extension("json.part").exists());
1483 }
1484
1485 #[cfg(windows)]
1486 #[test]
1487 fn only_a_held_file_is_a_momentary_refusal_on_windows() {
1488 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
1489 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
1490 assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
1491 }
1492
1493 fn at(second: i64, z: f64) -> CheckedFrame {
1495 CheckedFrame {
1496 frame: format!("frame-{second}.jpg").into(),
1497 captured_at: printobserver_types::Timestamp::from_unix_seconds(1_791_489_600 + second)
1498 .expect("a time"),
1499 print_z_mm: z,
1500 }
1501 }
1502
1503 fn heights(kept: &[CheckedFrame]) -> Vec<f64> {
1505 kept.iter().map(|checked| checked.print_z_mm).collect()
1506 }
1507
1508 #[test]
1512 fn after_a_planned_change_growth_is_measured_from_frames_after_it() {
1513 let state = tempfile::TempDir::new().expect("a state directory");
1514 let store =
1515 printobserver_store_sqlite::MemoryStore::new(state.path()).expect("an in-memory store");
1516 let alignments = super::Alignments::new(state.path(), None, std::sync::Arc::new(store))
1517 .expect("the verdicts' directories");
1518 let print_id = printobserver_types::PrintId::new();
1519 for (second, z) in [(0, 0.2), (60, 0.6)] {
1520 alignments.record_checked_frame(print_id, at(second, z), 0.4);
1521 }
1522 let before = alignments.growth_reference(print_id, 1.0, 0.4);
1523 assert_eq!(before.map(|checked| checked.print_z_mm), Some(0.6));
1524
1525 alignments.restart_growth(print_id);
1526 assert_eq!(alignments.growth_reference(print_id, 1.0, 0.4), None);
1527 alignments.record_checked_frame(print_id, at(3_000, 0.8), 0.4);
1528 alignments.record_checked_frame(print_id, at(3_120, 1.4), 0.4);
1529 let after = alignments.growth_reference(print_id, 1.4, 0.4);
1530 assert_eq!(
1531 after.map(|checked| checked.captured_at),
1532 Some(at(3_000, 0.8).captured_at)
1533 );
1534 alignments.restart_growth(print_id);
1536 alignments.restart_growth(print_id);
1537 assert!(alignments.checked_frames(print_id).is_empty());
1538 }
1539
1540 #[test]
1541 fn a_check_measures_from_the_newest_frame_far_enough_below_it() {
1542 let kept = [at(0, 0.2), at(60, 0.8), at(120, 2.0), at(180, 2.6)];
1543 assert_eq!(
1544 reference_in(&kept, 5.8, 3.0).map(|checked| checked.print_z_mm),
1545 Some(2.6)
1546 );
1547 assert_eq!(
1548 reference_in(&kept, 3.5, 3.0).map(|checked| checked.print_z_mm),
1549 Some(0.2)
1550 );
1551 assert_eq!(reference_in(&kept, 3.1, 3.0), None, "none is 3 mm below");
1552 }
1553
1554 #[test]
1555 fn only_what_a_later_check_can_measure_from_is_kept() {
1556 let mut kept = Vec::new();
1557 for (second, z) in [(0, 0.2), (60, 0.8), (120, 2.0), (180, 3.4), (240, 4.0)] {
1558 kept = kept_with(kept, at(second, z), 3.0);
1559 }
1560 assert_eq!(
1561 heights(&kept),
1562 [0.8, 2.0, 3.4, 4.0],
1563 "0.2 is below 0.8, which is itself 3 mm below 4.0, so no later check needs it"
1564 );
1565 assert_eq!(
1566 heights(&kept_with(kept, at(300, 1.0), 3.0)),
1567 [1.0],
1568 "a plan gone back down starts the record again"
1569 );
1570 }
1571
1572 #[test]
1573 fn the_oldest_checked_frames_go_past_the_most_kept() {
1574 let mut kept = Vec::new();
1575 for second in 0..=i64::try_from(MAX_CHECKED_FRAMES).expect("a count") {
1576 kept = kept_with(kept, at(second, 5.0), 3.0);
1577 }
1578 assert_eq!(kept.len(), MAX_CHECKED_FRAMES);
1579 assert_eq!(kept[0].captured_at, at(1, 5.0).captured_at);
1580 }
1581}