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 schema_version: crate::judgements::CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
681 frame_sha256: sha.to_owned(),
682 outcome: ViewOutcome::FrameMismatch,
683 view_correction: in_force.clone(),
684 reason: Some(reason.clone()),
685 landmarks: Vec::new(),
686 residual_px: None,
687 }));
688 if Self::alignment_due(&judged.alignment, judging).is_some() {
689 let failure = failure_of(error, calibration);
690 judged.records.extend(body_of(
691 &crate::judgements::FirstLayerAlignmentJudgedPayload {
692 verdict: crate::judgements::AlignmentJudgedVerdict::Failed,
693 offset_px: None,
694 correction_px: None,
695 match_strength: None,
696 reason: failure_sentence(&failure),
697 frame_sha256: sha.to_owned(),
698 view_correction: in_force.clone(),
699 },
700 ));
701 judged.alignment = PrintAlignment::Failed { reason: failure };
702 self.decide(print_id, &judged.alignment);
703 let mut state = self.view_state(print_id);
704 state.correction = None;
705 state.inconclusive = None;
706 self.keep_view_state(print_id, &state);
707 }
708 judged.correction = in_force.filter(|_| judged.alignment.passed());
709 judged.mismatch = Some(reason);
710 judged
711 }
712
713 #[expect(
722 clippy::too_many_arguments,
723 reason = "the one judgement's inputs and the two records it updates"
724 )]
725 fn judge_under_check(
726 &self,
727 print_id: PrintId,
728 calibration: &CameraCalibration,
729 landmarks: Vec<printobserver_panels::FoundLandmark>,
730 judging: &Judging<'_>,
731 checked: &CheckedCamera,
732 state: &mut CameraViewState,
733 mut judged: Judged,
734 ) -> Judged {
735 let sha = judging.frame_sha256;
736 if let Some(first) = Self::alignment_due(&judged.alignment, judging) {
737 self.record_first_layer(
738 print_id,
739 calibration,
740 &first,
741 judging,
742 checked,
743 state,
744 &mut judged,
745 );
746 }
747 let view = judge_found(calibration, landmarks, Some(&checked.correction));
748 if view.outcome == ViewOutcome::ViewRefitRejected {
749 judged.rejected.clone_from(&view.reason);
750 } else if view.outcome.drawable() {
751 judged.correction = Some(checked.correction.clone());
752 }
753 judged
754 .records
755 .extend(body_of(&crate::judgements::CameraViewJudgedPayload::of(
756 sha,
757 &view,
758 Some(checked.correction.clone()),
759 view.reason.clone(),
760 )));
761 judged.camera_check = Some(checked.id);
762 judged.inconclusive = state.inconclusive;
763 judged.view = Some((view.outcome, view.reason));
764 judged
765 }
766
767 #[expect(
771 clippy::too_many_arguments,
772 reason = "the one judgement's inputs and the two records it updates"
773 )]
774 fn record_first_layer(
775 &self,
776 print_id: PrintId,
777 calibration: &CameraCalibration,
778 first: &DueAlignment,
779 judging: &Judging<'_>,
780 checked: &CheckedCamera,
781 state: &mut CameraViewState,
782 judged: &mut Judged,
783 ) {
784 let Ok(judgement) = judge_first_layer(&FirstLayerInputs {
785 alignment: AlignmentInputs {
786 frame_jpeg: judging.frame_jpeg,
787 camera_snapshot_url: judging.camera_snapshot_url,
788 first_layer: &first.first_layer,
789 print_z_mm: first.print_z_mm,
790 calibration,
791 },
792 nozzle_xy_mm: first.nozzle_xy_mm,
793 }) else {
794 return;
797 };
798 let found = judgement.found;
799 let shift = |found: &printobserver_panels::AlignmentVerdict| {
800 printobserver_panels::alignment::correction_shift(
801 found,
802 &first.first_layer,
803 first.print_z_mm,
804 )
805 };
806 let (verdict, reason) = match judgement.verdict {
807 FirstLayerVerdict::Passed => (
808 crate::judgements::AlignmentJudgedVerdict::Passed,
809 "clearly_found".to_owned(),
810 ),
811 FirstLayerVerdict::Inconclusive(why) => (
812 crate::judgements::AlignmentJudgedVerdict::Inconclusive,
813 why.as_str().to_owned(),
814 ),
815 };
816 judged.records.extend(body_of(
817 &crate::judgements::FirstLayerAlignmentJudgedPayload {
818 verdict,
819 offset_px: found.map(|found| found.offset_px),
820 correction_px: (judgement.verdict == FirstLayerVerdict::Passed)
821 .then(|| found.as_ref().map(shift))
822 .flatten(),
823 match_strength: found.map(|found| found.match_strength),
824 reason,
825 frame_sha256: judging.frame_sha256.to_owned(),
826 view_correction: Some(checked.correction.clone()),
827 },
828 ));
829 match (judgement.verdict, found) {
830 (FirstLayerVerdict::Passed, Some(found)) => {
831 judged.alignment = PrintAlignment::Passed {
832 offset_px: found.offset_px,
833 correction_px: shift(&found),
834 };
835 state.inconclusive = None;
836 }
837 (FirstLayerVerdict::Inconclusive(why), _) => {
838 judged.alignment = PrintAlignment::Pending;
839 state.inconclusive = Some(why);
840 }
841 (FirstLayerVerdict::Passed, None) => return,
842 }
843 self.decide(print_id, &judged.alignment);
844 self.keep_view_state(print_id, state);
845 }
846
847 #[expect(
850 clippy::too_many_arguments,
851 reason = "the one judgement's inputs and the two records it updates"
852 )]
853 fn judge_alignment(
854 &self,
855 print_id: PrintId,
856 calibration: &CameraCalibration,
857 landmarks: Vec<printobserver_panels::FoundLandmark>,
858 first: &DueAlignment,
859 judging: &Judging<'_>,
860 in_force: Option<ViewCorrection>,
861 state: &mut CameraViewState,
862 judged: &mut Judged,
863 ) -> ViewJudgement {
864 let sha = judging.frame_sha256;
865 let uncorrected = judge_found(calibration, landmarks.clone(), None);
866 let judgement = judge_first_layer(&FirstLayerInputs {
867 alignment: AlignmentInputs {
868 frame_jpeg: judging.frame_jpeg,
869 camera_snapshot_url: judging.camera_snapshot_url,
870 first_layer: &first.first_layer,
871 print_z_mm: first.print_z_mm,
872 calibration,
873 },
874 nozzle_xy_mm: first.nozzle_xy_mm,
875 });
876 let Ok(judgement) = judgement else {
877 judged.records.extend(view_record(sha, &uncorrected, None));
881 return uncorrected;
882 };
883 let found = judgement.found;
884 let (verdict, correction_px, reason) = match judgement.verdict {
885 FirstLayerVerdict::Passed => (
886 crate::judgements::AlignmentJudgedVerdict::Passed,
887 found.map(|found| {
888 printobserver_panels::alignment::correction_shift(
889 &found,
890 &first.first_layer,
891 first.print_z_mm,
892 )
893 }),
894 "clearly_found".to_owned(),
895 ),
896 FirstLayerVerdict::Inconclusive(why) => (
897 crate::judgements::AlignmentJudgedVerdict::Inconclusive,
898 None,
899 why.as_str().to_owned(),
900 ),
901 };
902 judged.records.extend(body_of(
903 &crate::judgements::FirstLayerAlignmentJudgedPayload {
904 verdict,
905 offset_px: found.map(|found| found.offset_px),
906 correction_px,
907 match_strength: found.map(|found| found.match_strength),
908 reason,
909 frame_sha256: sha.to_owned(),
910 view_correction: in_force,
911 },
912 ));
913 match (judgement.verdict, found) {
914 (FirstLayerVerdict::Passed, Some(found)) => {
915 let shift = printobserver_panels::alignment::correction_shift(
916 &found,
917 &first.first_layer,
918 first.print_z_mm,
919 );
920 eprintln!(
921 "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",
922 found.shift_px[0],
923 found.shift_px[1],
924 first.print_z_mm,
925 found.match_strength,
926 shift[0],
927 shift[1]
928 );
929 let correction = ViewCorrection::translation(shift, uncorrected.agreeing());
930 judged.alignment = PrintAlignment::Passed {
931 offset_px: found.offset_px,
932 correction_px: shift,
933 };
934 self.decide(print_id, &judged.alignment);
935 state.correction = Some(correction.clone());
936 state.inconclusive = None;
937 self.keep_view_state(print_id, state);
938 if uncorrected.moved(calibration) {
939 judged
940 .records
941 .extend(body_of(&crate::judgements::CameraViewRefitPayload {
942 frame_sha256: sha.to_owned(),
943 view_correction: correction.clone(),
944 }));
945 }
946 let view = judge_found(calibration, landmarks, Some(&correction));
947 judged
948 .records
949 .extend(view_record(sha, &view, Some(correction.clone())));
950 judged.correction = Some(correction);
951 view
952 }
953 (FirstLayerVerdict::Inconclusive(why), _) => {
954 judged.alignment = PrintAlignment::Pending;
957 self.decide(print_id, &judged.alignment);
958 state.correction = None;
959 state.inconclusive = Some(why);
960 self.keep_view_state(print_id, state);
961 judged.records.extend(view_record(sha, &uncorrected, None));
962 uncorrected
963 }
964 (FirstLayerVerdict::Passed, None) => {
965 judged.records.extend(view_record(sha, &uncorrected, None));
966 uncorrected
967 }
968 }
969 }
970
971 fn alignment_due(alignment: &PrintAlignment, judging: &Judging<'_>) -> Option<DueAlignment> {
974 let asked = match judging.alignment {
975 AlignmentJudging::Never => false,
976 AlignmentJudging::WhilePending => *alignment == PrintAlignment::Pending,
977 AlignmentJudging::Afresh => true,
978 };
979 if !asked {
980 return None;
981 }
982 let plan = judging.plan?;
983 let index = &plan.index;
984 let position = plan.file_position_bytes;
985 let (first, ends) = index.first_object_layer()?;
986 if position <= ends {
987 return None;
988 }
989 Some(DueAlignment {
990 first_layer: index.layer_toolpath(first).ok()?,
991 print_z_mm: index
992 .layer_at(position)
993 .and_then(|layer| index.layer_z_mm(layer))?,
994 nozzle_xy_mm: index.planned_head_at(position).ok().flatten(),
995 })
996 }
997
998 pub async fn sweep(&self) {
1014 let Ok(open) = self.prints.open_prints().await else {
1015 return;
1016 };
1017 let open: Vec<String> = open
1018 .iter()
1019 .flat_map(|print| {
1020 [
1021 format!("{}.json", print.id),
1022 format!("{}.json.part", print.id),
1023 ]
1024 })
1025 .collect();
1026 for directory in [
1027 &self.directory,
1028 &self.previous_directory,
1029 &self.checked_directory,
1030 &self.view_directory,
1031 ] {
1032 let Ok(entries) = std::fs::read_dir(directory) else {
1033 continue;
1034 };
1035 for entry in entries.flatten() {
1036 let name = entry.file_name();
1037 if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
1038 let _ = std::fs::remove_file(entry.path());
1039 }
1040 }
1041 }
1042 }
1043}
1044
1045fn reference_in(kept: &[CheckedFrame], print_z_mm: f64, rise_mm: f64) -> Option<&CheckedFrame> {
1048 kept.iter()
1049 .rev()
1050 .find(|checked| checked.print_z_mm <= print_z_mm - rise_mm)
1051}
1052
1053fn kept_with(
1058 mut kept: Vec<CheckedFrame>,
1059 checked: CheckedFrame,
1060 rise_mm: f64,
1061) -> Vec<CheckedFrame> {
1062 if kept
1063 .last()
1064 .is_some_and(|last| checked.print_z_mm < last.print_z_mm)
1065 {
1066 kept.clear();
1067 }
1068 if let Some(reference) = kept
1069 .iter()
1070 .rposition(|earlier| earlier.print_z_mm <= checked.print_z_mm - rise_mm)
1071 {
1072 kept.drain(..reference);
1073 }
1074 kept.push(checked);
1075 if kept.len() > MAX_CHECKED_FRAMES {
1076 kept.drain(..kept.len() - MAX_CHECKED_FRAMES);
1077 }
1078 kept
1079}
1080
1081const REPLACE_ATTEMPTS: u32 = 20;
1085const REPLACE_PAUSE: Duration = Duration::from_millis(25);
1086
1087fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
1100 let held = path.with_extension("json.part");
1101 attempt_while_refused(
1102 || {
1103 std::fs::write(&held, bytes)?;
1104 std::fs::rename(&held, path)
1105 },
1106 refused_for_a_moment,
1107 REPLACE_ATTEMPTS,
1108 REPLACE_PAUSE,
1109 )
1110 .inspect_err(|_| {
1111 let _ = std::fs::remove_file(&held);
1112 })
1113}
1114
1115fn attempt_while_refused(
1118 mut attempt: impl FnMut() -> std::io::Result<()>,
1119 refused: impl Fn(&std::io::Error) -> bool,
1120 attempts: u32,
1121 pause: Duration,
1122) -> std::io::Result<()> {
1123 let mut made = 1;
1124 loop {
1125 match attempt() {
1126 Err(error) if made < attempts && refused(&error) => {
1127 std::thread::sleep(pause);
1128 made += 1;
1129 }
1130 answered => return answered,
1131 }
1132 }
1133}
1134
1135#[cfg(windows)]
1138fn refused_for_a_moment(error: &std::io::Error) -> bool {
1139 matches!(error.raw_os_error(), Some(5 | 32))
1140}
1141
1142#[cfg(not(windows))]
1145fn refused_for_a_moment(_error: &std::io::Error) -> bool {
1146 false
1147}
1148
1149fn size_of(text: &str) -> [u32; 2] {
1151 let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
1152 [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
1153}
1154
1155fn said(verdict: &PrintAlignment) -> String {
1157 match verdict {
1158 PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
1159 PrintAlignment::Pending => "pending".to_owned(),
1160 PrintAlignment::Passed {
1161 offset_px,
1162 correction_px,
1163 } => format!(
1164 "passed, offset {offset_px:.1} px, corrected by [{:.0}, {:.0}] px",
1165 correction_px[0], correction_px[1]
1166 ),
1167 PrintAlignment::Failed {
1168 reason: AlignmentFailure::Offset { offset_px },
1169 } => format!("failed, offset {offset_px:.1} px"),
1170 PrintAlignment::Failed {
1171 reason: AlignmentFailure::Resolution { expected, got },
1172 } => format!(
1173 "failed: the camera's frames are {}x{}, the calibration's {}x{}",
1174 got[0], got[1], expected[0], expected[1]
1175 ),
1176 PrintAlignment::Failed {
1177 reason: AlignmentFailure::Stream,
1178 } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
1179 }
1180}
1181
1182#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1184#[serde(crate = "printobserver_types::serde")]
1185struct CameraViewState {
1186 #[serde(default)]
1188 correction: Option<ViewCorrection>,
1189 #[serde(default)]
1192 inconclusive: Option<InconclusiveReason>,
1193 #[serde(default)]
1195 last_check_image: Option<LastCheckImage>,
1196 #[serde(default)]
1199 camera_check: Option<CheckedCamera>,
1200}
1201
1202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1204#[serde(crate = "printobserver_types::serde")]
1205struct CheckedCamera {
1206 id: printobserver_core::CameraCheckId,
1208 correction: ViewCorrection,
1210}
1211
1212#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1214#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1215#[schemars(crate = "printobserver_types::schemars")]
1216pub struct LastCheckImage {
1217 pub at: Timestamp,
1219 pub kind: ImageKind,
1221 pub fallback: Option<ImageFallback>,
1223}
1224
1225impl Sample for LastCheckImage {
1226 fn sample_full() -> Self {
1227 Self {
1228 at: Timestamp::sample_full(),
1229 kind: ImageKind::WholeFrame,
1230 fallback: Some(ImageFallback::sample_full()),
1231 }
1232 }
1233
1234 fn sample_minimal() -> Self {
1235 Self {
1236 at: Timestamp::sample_full(),
1237 kind: ImageKind::ThreePanel,
1238 fallback: None,
1239 }
1240 }
1241}
1242
1243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1245pub enum AlignmentJudging {
1246 Never,
1248 WhilePending,
1250 Afresh,
1253}
1254
1255impl AlignmentJudging {
1256 #[must_use]
1260 pub const fn of_recheck(paused: bool) -> Self {
1261 if paused { Self::Never } else { Self::Afresh }
1262 }
1263}
1264
1265#[derive(Debug, Clone, Copy)]
1267pub struct Judging<'a> {
1268 pub frame_jpeg: &'a [u8],
1270 pub frame_sha256: &'a str,
1272 pub camera_snapshot_url: &'a str,
1274 pub plan: Option<&'a PlanPosition>,
1276 pub alignment: AlignmentJudging,
1278}
1279
1280#[derive(Debug, Clone, PartialEq)]
1282pub struct Judged {
1283 pub records: Vec<EventBody>,
1285 pub alignment: PrintAlignment,
1287 pub correction: Option<ViewCorrection>,
1290 pub view: Option<(ViewOutcome, Option<String>)>,
1293 pub rejected: Option<String>,
1296 pub mismatch: Option<String>,
1298 pub unreadable: Option<String>,
1300 pub inconclusive: Option<InconclusiveReason>,
1303 pub camera_check: Option<printobserver_core::CameraCheckId>,
1306}
1307
1308impl Judged {
1309 #[must_use]
1313 pub fn nothing_to_judge(alignment: PrintAlignment, kept_with: Option<EventBody>) -> Self {
1314 Self {
1315 records: kept_with.into_iter().collect(),
1316 ..Self::unjudged(alignment)
1317 }
1318 }
1319
1320 const fn unjudged(alignment: PrintAlignment) -> Self {
1322 Self {
1323 records: Vec::new(),
1324 alignment,
1325 correction: None,
1326 view: None,
1327 rejected: None,
1328 mismatch: None,
1329 unreadable: None,
1330 inconclusive: None,
1331 camera_check: None,
1332 }
1333 }
1334}
1335
1336impl PrintAlignment {
1337 #[must_use]
1339 pub const fn passed(&self) -> bool {
1340 matches!(self, Self::Passed { .. })
1341 }
1342}
1343
1344struct DueAlignment {
1346 first_layer: printobserver_core::LayerToolpath,
1348 print_z_mm: f64,
1350 nozzle_xy_mm: Option<[f64; 2]>,
1352}
1353
1354fn body_of<P: EventPayload>(payload: &P) -> Option<EventBody> {
1357 EventBody::of(payload).ok()
1358}
1359
1360fn view_record(
1364 frame_sha256: &str,
1365 view: &ViewJudgement,
1366 view_correction: Option<ViewCorrection>,
1367) -> Option<EventBody> {
1368 let reason = if view.outcome == ViewOutcome::Refit {
1369 Some(crate::check_images::CALIBRATION_STALE.to_owned())
1370 } else {
1371 view.reason.clone()
1372 };
1373 body_of(&crate::judgements::CameraViewJudgedPayload::of(
1374 frame_sha256,
1375 view,
1376 view_correction,
1377 reason,
1378 ))
1379}
1380
1381fn failure_of(error: &ComposeError, calibration: &CameraCalibration) -> AlignmentFailure {
1383 match error {
1384 ComposeError::FrameMismatch {
1385 field: FrameField::Resolution,
1386 got,
1387 ..
1388 } => AlignmentFailure::Resolution {
1389 expected: calibration.image_size_px,
1390 got: size_of(got),
1391 },
1392 _ => AlignmentFailure::Stream,
1393 }
1394}
1395
1396#[must_use]
1398pub fn failure_sentence(failure: &AlignmentFailure) -> String {
1399 match failure {
1400 AlignmentFailure::Offset { offset_px } => format!(
1401 "the printed first layer lies {offset_px:.1} px from where the calibration projects it"
1402 ),
1403 AlignmentFailure::Resolution { expected, got } => format!(
1404 "the camera's frames are {}x{} and the calibration's {}x{}",
1405 got[0], got[1], expected[0], expected[1]
1406 ),
1407 AlignmentFailure::Stream => {
1408 "the camera is not the stream the calibration was fitted on".to_owned()
1409 }
1410 }
1411}
1412
1413#[cfg(test)]
1414mod tests {
1415 use super::{CheckedFrame, MAX_CHECKED_FRAMES, attempt_while_refused, kept_with, reference_in};
1416 use std::cell::Cell;
1417 use std::io::{Error, ErrorKind};
1418 use std::time::Duration;
1419
1420 fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
1423 move || {
1424 made.set(made.get() + 1);
1425 if made.get() <= refusals {
1426 Err(Error::from(ErrorKind::PermissionDenied))
1427 } else {
1428 Ok(())
1429 }
1430 }
1431 }
1432
1433 #[test]
1434 fn a_momentary_refusal_is_attempted_again_until_it_passes() {
1435 let made = Cell::new(0);
1436 let answered =
1437 attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
1438 assert!(answered.is_ok(), "{answered:?}");
1439 assert_eq!(made.get(), 3);
1440 }
1441
1442 #[test]
1443 fn a_refusal_that_outlasts_every_attempt_is_answered() {
1444 let made = Cell::new(0);
1445 let answered =
1446 attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
1447 assert_eq!(
1448 answered.map_err(|error| error.kind()),
1449 Err(ErrorKind::PermissionDenied)
1450 );
1451 assert_eq!(made.get(), 4);
1452 }
1453
1454 #[test]
1455 fn a_refusal_that_is_not_momentary_is_answered_at_once() {
1456 let made = Cell::new(0);
1457 let answered =
1458 attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
1459 assert!(answered.is_err());
1460 assert_eq!(made.get(), 1);
1461 }
1462
1463 #[cfg(windows)]
1467 #[test]
1468 fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
1469 use std::os::windows::fs::OpenOptionsExt;
1470 let directory = tempfile::TempDir::new().expect("a directory");
1471 let path = directory.path().join("record.json");
1472 std::fs::write(&path, b"before").expect("a record");
1473 let held = std::fs::OpenOptions::new()
1474 .read(true)
1475 .share_mode(0)
1476 .open(&path)
1477 .expect("the record held");
1478 let release = std::thread::spawn(move || {
1479 std::thread::sleep(Duration::from_millis(150));
1480 drop(held);
1481 });
1482 super::replace_file(&path, b"after").expect("the record replaced");
1483 release.join().expect("the handle let go");
1484 assert_eq!(std::fs::read(&path).expect("the record"), b"after");
1485 assert!(!path.with_extension("json.part").exists());
1486 }
1487
1488 #[cfg(windows)]
1489 #[test]
1490 fn only_a_held_file_is_a_momentary_refusal_on_windows() {
1491 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
1492 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
1493 assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
1494 }
1495
1496 fn at(second: i64, z: f64) -> CheckedFrame {
1498 CheckedFrame {
1499 frame: format!("frame-{second}.jpg").into(),
1500 captured_at: printobserver_types::Timestamp::from_unix_seconds(1_791_489_600 + second)
1501 .expect("a time"),
1502 print_z_mm: z,
1503 }
1504 }
1505
1506 fn heights(kept: &[CheckedFrame]) -> Vec<f64> {
1508 kept.iter().map(|checked| checked.print_z_mm).collect()
1509 }
1510
1511 #[test]
1515 fn after_a_planned_change_growth_is_measured_from_frames_after_it() {
1516 let state = tempfile::TempDir::new().expect("a state directory");
1517 let store =
1518 printobserver_store_sqlite::MemoryStore::new(state.path()).expect("an in-memory store");
1519 let alignments = super::Alignments::new(state.path(), None, std::sync::Arc::new(store))
1520 .expect("the verdicts' directories");
1521 let print_id = printobserver_types::PrintId::new();
1522 for (second, z) in [(0, 0.2), (60, 0.6)] {
1523 alignments.record_checked_frame(print_id, at(second, z), 0.4);
1524 }
1525 let before = alignments.growth_reference(print_id, 1.0, 0.4);
1526 assert_eq!(before.map(|checked| checked.print_z_mm), Some(0.6));
1527
1528 alignments.restart_growth(print_id);
1529 assert_eq!(alignments.growth_reference(print_id, 1.0, 0.4), None);
1530 alignments.record_checked_frame(print_id, at(3_000, 0.8), 0.4);
1531 alignments.record_checked_frame(print_id, at(3_120, 1.4), 0.4);
1532 let after = alignments.growth_reference(print_id, 1.4, 0.4);
1533 assert_eq!(
1534 after.map(|checked| checked.captured_at),
1535 Some(at(3_000, 0.8).captured_at)
1536 );
1537 alignments.restart_growth(print_id);
1539 alignments.restart_growth(print_id);
1540 assert!(alignments.checked_frames(print_id).is_empty());
1541 }
1542
1543 #[test]
1544 fn a_check_measures_from_the_newest_frame_far_enough_below_it() {
1545 let kept = [at(0, 0.2), at(60, 0.8), at(120, 2.0), at(180, 2.6)];
1546 assert_eq!(
1547 reference_in(&kept, 5.8, 3.0).map(|checked| checked.print_z_mm),
1548 Some(2.6)
1549 );
1550 assert_eq!(
1551 reference_in(&kept, 3.5, 3.0).map(|checked| checked.print_z_mm),
1552 Some(0.2)
1553 );
1554 assert_eq!(reference_in(&kept, 3.1, 3.0), None, "none is 3 mm below");
1555 }
1556
1557 #[test]
1558 fn only_what_a_later_check_can_measure_from_is_kept() {
1559 let mut kept = Vec::new();
1560 for (second, z) in [(0, 0.2), (60, 0.8), (120, 2.0), (180, 3.4), (240, 4.0)] {
1561 kept = kept_with(kept, at(second, z), 3.0);
1562 }
1563 assert_eq!(
1564 heights(&kept),
1565 [0.8, 2.0, 3.4, 4.0],
1566 "0.2 is below 0.8, which is itself 3 mm below 4.0, so no later check needs it"
1567 );
1568 assert_eq!(
1569 heights(&kept_with(kept, at(300, 1.0), 3.0)),
1570 [1.0],
1571 "a plan gone back down starts the record again"
1572 );
1573 }
1574
1575 #[test]
1576 fn the_oldest_checked_frames_go_past_the_most_kept() {
1577 let mut kept = Vec::new();
1578 for second in 0..=i64::try_from(MAX_CHECKED_FRAMES).expect("a count") {
1579 kept = kept_with(kept, at(second, 5.0), 3.0);
1580 }
1581 assert_eq!(kept.len(), MAX_CHECKED_FRAMES);
1582 assert_eq!(kept[0].captured_at, at(1, 5.0).captured_at);
1583 }
1584}