1use std::path::{Path, PathBuf};
29use std::sync::Arc;
30use std::time::Duration;
31
32use printobserver_core::store::PrintStore;
33use printobserver_core::{ActiveJob, Supervisor};
34use printobserver_panels::alignment::SEARCH_PX;
35use printobserver_panels::{
36 AlignmentInputs, CameraCalibration, ComposeError, FrameField, verify_first_layer_alignment,
37};
38use printobserver_types::PrintId;
39use printobserver_types::contract::Sample;
40use printobserver_types::schemars::JsonSchema;
41use printobserver_types::serde::{Deserialize, Serialize};
42
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
45#[serde(
46 crate = "printobserver_types::serde",
47 tag = "failure",
48 rename_all = "snake_case"
49)]
50#[schemars(crate = "printobserver_types::schemars")]
51pub enum AlignmentFailure {
52 Offset {
55 offset_px: f64,
57 },
58 Resolution {
60 expected: [u32; 2],
62 got: [u32; 2],
64 },
65 Stream,
67}
68
69#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
72#[serde(
73 crate = "printobserver_types::serde",
74 tag = "verdict",
75 rename_all = "snake_case"
76)]
77#[schemars(crate = "printobserver_types::schemars")]
78pub enum PrintAlignment {
79 Unavailable,
82 Pending,
85 Passed {
87 offset_px: f64,
89 },
90 Failed {
92 reason: AlignmentFailure,
94 },
95}
96
97impl Sample for PrintAlignment {
98 fn sample_full() -> Self {
99 Self::Passed { offset_px: 14.5 }
100 }
101
102 fn sample_minimal() -> Self {
103 Self::Pending
104 }
105
106 fn sample_alternates() -> Vec<Self> {
107 vec![
108 Self::Unavailable,
109 Self::Failed {
110 reason: AlignmentFailure::Offset { offset_px: 48.5 },
111 },
112 Self::Failed {
113 reason: AlignmentFailure::Resolution {
114 expected: [1920, 1080],
115 got: [1280, 720],
116 },
117 },
118 Self::Failed {
119 reason: AlignmentFailure::Stream,
120 },
121 ]
122 }
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127#[serde(crate = "printobserver_types::serde")]
128pub struct PreviousCheck {
129 pub frame: PathBuf,
131 pub captured_at: printobserver_types::Timestamp,
133}
134
135#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137#[serde(crate = "printobserver_types::serde")]
138pub struct CheckedFrame {
139 pub frame: PathBuf,
141 pub captured_at: printobserver_types::Timestamp,
143 pub print_z_mm: f64,
145}
146
147const MAX_CHECKED_FRAMES: usize = 512;
149
150pub struct Alignments {
153 directory: PathBuf,
155 previous_directory: PathBuf,
157 checked_directory: PathBuf,
159 calibration: Option<Arc<CameraCalibration>>,
161 prints: Arc<dyn PrintStore>,
163}
164
165impl core::fmt::Debug for Alignments {
166 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
167 formatter
168 .debug_struct("Alignments")
169 .field("directory", &self.directory)
170 .field("calibrated", &self.calibration.is_some())
171 .finish_non_exhaustive()
172 }
173}
174
175#[must_use]
177pub fn verdict_dir(state_dir: &Path) -> PathBuf {
178 state_dir.join("alignment")
179}
180
181#[must_use]
184pub fn previous_check_dir(state_dir: &Path) -> PathBuf {
185 state_dir.join("previous-check")
186}
187
188#[must_use]
191pub fn checked_frames_dir(state_dir: &Path) -> PathBuf {
192 state_dir.join("checked-frames")
193}
194
195impl Alignments {
196 pub fn new(
202 state_dir: &Path,
203 calibration: Option<Arc<CameraCalibration>>,
204 prints: Arc<dyn PrintStore>,
205 ) -> std::io::Result<Self> {
206 let directory = verdict_dir(state_dir);
207 std::fs::create_dir_all(&directory)?;
208 let previous_directory = previous_check_dir(state_dir);
209 std::fs::create_dir_all(&previous_directory)?;
210 let checked_directory = checked_frames_dir(state_dir);
211 std::fs::create_dir_all(&checked_directory)?;
212 Ok(Self {
213 directory,
214 previous_directory,
215 checked_directory,
216 calibration,
217 prints,
218 })
219 }
220
221 fn path_of(&self, print_id: PrintId) -> PathBuf {
223 self.directory.join(format!("{print_id}.json"))
224 }
225
226 #[must_use]
228 pub fn calibration(&self) -> Option<&CameraCalibration> {
229 self.calibration.as_deref()
230 }
231
232 fn previous_path_of(&self, print_id: PrintId) -> PathBuf {
234 self.previous_directory.join(format!("{print_id}.json"))
235 }
236
237 #[must_use]
240 pub fn previous_check(&self, print_id: PrintId) -> Option<PreviousCheck> {
241 std::fs::read(self.previous_path_of(print_id))
242 .ok()
243 .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
244 }
245
246 pub fn record_check(&self, print_id: PrintId, check: &PreviousCheck) {
257 let Ok(bytes) = printobserver_types::serde_json::to_vec(check) else {
258 return;
259 };
260 if let Err(error) = replace_file(&self.previous_path_of(print_id), &bytes) {
261 eprintln!(
262 "printobserver: print {print_id}: the last check's frame could not be recorded, so the next check shows an older one or none: {error}"
263 );
264 }
265 }
266
267 fn checked_path_of(&self, print_id: PrintId) -> PathBuf {
269 self.checked_directory.join(format!("{print_id}.json"))
270 }
271
272 #[must_use]
276 pub fn checked_frames(&self, print_id: PrintId) -> Vec<CheckedFrame> {
277 std::fs::read(self.checked_path_of(print_id))
278 .ok()
279 .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
280 .unwrap_or_default()
281 }
282
283 pub fn restart_growth(&self, print_id: PrintId) {
290 let path = self.checked_path_of(print_id);
291 if let Err(error) = std::fs::remove_file(&path)
292 && error.kind() != std::io::ErrorKind::NotFound
293 {
294 eprintln!(
295 "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}"
296 );
297 }
298 }
299
300 #[must_use]
303 pub fn growth_reference(
304 &self,
305 print_id: PrintId,
306 print_z_mm: f64,
307 rise_mm: f64,
308 ) -> Option<CheckedFrame> {
309 reference_in(&self.checked_frames(print_id), print_z_mm, rise_mm).cloned()
310 }
311
312 pub fn record_checked_frame(&self, print_id: PrintId, checked: CheckedFrame, rise_mm: f64) {
321 let kept = kept_with(self.checked_frames(print_id), checked, rise_mm);
322 let Ok(bytes) = printobserver_types::serde_json::to_vec(&kept) else {
323 return;
324 };
325 if let Err(error) = replace_file(&self.checked_path_of(print_id), &bytes) {
326 eprintln!(
327 "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}"
328 );
329 }
330 }
331
332 #[must_use]
334 pub fn print_alignment(&self, print_id: PrintId) -> PrintAlignment {
335 if self.calibration.is_none() {
336 return PrintAlignment::Unavailable;
337 }
338 std::fs::read(self.path_of(print_id))
339 .ok()
340 .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
341 .unwrap_or(PrintAlignment::Pending)
342 }
343
344 pub async fn check(
348 &self,
349 supervisor: &Supervisor,
350 active: ActiveJob,
351 ) -> Option<PrintAlignment> {
352 let calibration = self.calibration.as_ref()?;
353 if self.print_alignment(active.print_id) != PrintAlignment::Pending {
356 return None;
357 }
358 let position = u64::try_from(active.file_position_bytes?).ok()?;
359 let index = supervisor.print_gcode_index(active.print_id).await?;
360 let Some((first, ends)) = index.first_object_layer() else {
361 return self.decide(active.print_id, PrintAlignment::Unavailable);
362 };
363 if position <= ends {
364 return None;
365 }
366 let first_layer = index.layer_toolpath(first).ok()?;
367 let print_z_mm = index
368 .layer_at(position)
369 .and_then(|layer| index.layer_z_mm(layer))?;
370 let (url, frame) = supervisor.fetch_camera_frame(active.print_id).await?;
371 let verdict = match verify_first_layer_alignment(&AlignmentInputs {
372 frame_jpeg: &frame,
373 camera_snapshot_url: &url,
374 first_layer: &first_layer,
375 print_z_mm,
376 calibration,
377 }) {
378 Ok(found) if found.passed => PrintAlignment::Passed {
379 offset_px: found.offset_px,
380 },
381 Ok(found) => PrintAlignment::Failed {
382 reason: AlignmentFailure::Offset {
383 offset_px: found.offset_px,
384 },
385 },
386 Err(ComposeError::FrameMismatch {
387 field: FrameField::Resolution,
388 got,
389 ..
390 }) => PrintAlignment::Failed {
391 reason: AlignmentFailure::Resolution {
392 expected: calibration.image_size_px,
393 got: size_of(&got),
394 },
395 },
396 Err(ComposeError::FrameMismatch {
397 field: FrameField::Stream,
398 ..
399 }) => PrintAlignment::Failed {
400 reason: AlignmentFailure::Stream,
401 },
402 Err(ComposeError::OutlineOffFrame) => PrintAlignment::Failed {
405 reason: AlignmentFailure::Offset {
406 offset_px: f64::from(SEARCH_PX),
407 },
408 },
409 Err(_) => return None,
410 };
411 self.decide(active.print_id, verdict)
412 }
413
414 fn decide(&self, print_id: PrintId, verdict: PrintAlignment) -> Option<PrintAlignment> {
421 let bytes = printobserver_types::serde_json::to_vec(&verdict).ok()?;
422 replace_file(&self.path_of(print_id), &bytes).ok()?;
423 eprintln!(
424 "printobserver: print {print_id}: first-layer alignment {}",
425 said(&verdict)
426 );
427 Some(verdict)
428 }
429
430 pub async fn sweep(&self) {
446 let Ok(open) = self.prints.open_prints().await else {
447 return;
448 };
449 let open: Vec<String> = open
450 .iter()
451 .flat_map(|print| {
452 [
453 format!("{}.json", print.id),
454 format!("{}.json.part", print.id),
455 ]
456 })
457 .collect();
458 for directory in [
459 &self.directory,
460 &self.previous_directory,
461 &self.checked_directory,
462 ] {
463 let Ok(entries) = std::fs::read_dir(directory) else {
464 continue;
465 };
466 for entry in entries.flatten() {
467 let name = entry.file_name();
468 if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
469 let _ = std::fs::remove_file(entry.path());
470 }
471 }
472 }
473 }
474}
475
476fn reference_in(kept: &[CheckedFrame], print_z_mm: f64, rise_mm: f64) -> Option<&CheckedFrame> {
479 kept.iter()
480 .rev()
481 .find(|checked| checked.print_z_mm <= print_z_mm - rise_mm)
482}
483
484fn kept_with(
489 mut kept: Vec<CheckedFrame>,
490 checked: CheckedFrame,
491 rise_mm: f64,
492) -> Vec<CheckedFrame> {
493 if kept
494 .last()
495 .is_some_and(|last| checked.print_z_mm < last.print_z_mm)
496 {
497 kept.clear();
498 }
499 if let Some(reference) = kept
500 .iter()
501 .rposition(|earlier| earlier.print_z_mm <= checked.print_z_mm - rise_mm)
502 {
503 kept.drain(..reference);
504 }
505 kept.push(checked);
506 if kept.len() > MAX_CHECKED_FRAMES {
507 kept.drain(..kept.len() - MAX_CHECKED_FRAMES);
508 }
509 kept
510}
511
512const REPLACE_ATTEMPTS: u32 = 20;
516const REPLACE_PAUSE: Duration = Duration::from_millis(25);
517
518fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
531 let held = path.with_extension("json.part");
532 attempt_while_refused(
533 || {
534 std::fs::write(&held, bytes)?;
535 std::fs::rename(&held, path)
536 },
537 refused_for_a_moment,
538 REPLACE_ATTEMPTS,
539 REPLACE_PAUSE,
540 )
541 .inspect_err(|_| {
542 let _ = std::fs::remove_file(&held);
543 })
544}
545
546fn attempt_while_refused(
549 mut attempt: impl FnMut() -> std::io::Result<()>,
550 refused: impl Fn(&std::io::Error) -> bool,
551 attempts: u32,
552 pause: Duration,
553) -> std::io::Result<()> {
554 let mut made = 1;
555 loop {
556 match attempt() {
557 Err(error) if made < attempts && refused(&error) => {
558 std::thread::sleep(pause);
559 made += 1;
560 }
561 answered => return answered,
562 }
563 }
564}
565
566#[cfg(windows)]
569fn refused_for_a_moment(error: &std::io::Error) -> bool {
570 matches!(error.raw_os_error(), Some(5 | 32))
571}
572
573#[cfg(not(windows))]
576fn refused_for_a_moment(_error: &std::io::Error) -> bool {
577 false
578}
579
580fn size_of(text: &str) -> [u32; 2] {
582 let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
583 [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
584}
585
586fn said(verdict: &PrintAlignment) -> String {
588 match verdict {
589 PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
590 PrintAlignment::Pending => "pending".to_owned(),
591 PrintAlignment::Passed { offset_px } => format!("passed, offset {offset_px:.1} px"),
592 PrintAlignment::Failed {
593 reason: AlignmentFailure::Offset { offset_px },
594 } => format!("failed, offset {offset_px:.1} px"),
595 PrintAlignment::Failed {
596 reason: AlignmentFailure::Resolution { expected, got },
597 } => format!(
598 "failed: the camera's frames are {}x{}, the calibration's {}x{}",
599 got[0], got[1], expected[0], expected[1]
600 ),
601 PrintAlignment::Failed {
602 reason: AlignmentFailure::Stream,
603 } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
604 }
605}
606
607#[cfg(test)]
608mod tests {
609 use super::{CheckedFrame, MAX_CHECKED_FRAMES, attempt_while_refused, kept_with, reference_in};
610 use std::cell::Cell;
611 use std::io::{Error, ErrorKind};
612 use std::time::Duration;
613
614 fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
617 move || {
618 made.set(made.get() + 1);
619 if made.get() <= refusals {
620 Err(Error::from(ErrorKind::PermissionDenied))
621 } else {
622 Ok(())
623 }
624 }
625 }
626
627 #[test]
628 fn a_momentary_refusal_is_attempted_again_until_it_passes() {
629 let made = Cell::new(0);
630 let answered =
631 attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
632 assert!(answered.is_ok(), "{answered:?}");
633 assert_eq!(made.get(), 3);
634 }
635
636 #[test]
637 fn a_refusal_that_outlasts_every_attempt_is_answered() {
638 let made = Cell::new(0);
639 let answered =
640 attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
641 assert_eq!(
642 answered.map_err(|error| error.kind()),
643 Err(ErrorKind::PermissionDenied)
644 );
645 assert_eq!(made.get(), 4);
646 }
647
648 #[test]
649 fn a_refusal_that_is_not_momentary_is_answered_at_once() {
650 let made = Cell::new(0);
651 let answered =
652 attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
653 assert!(answered.is_err());
654 assert_eq!(made.get(), 1);
655 }
656
657 #[cfg(windows)]
661 #[test]
662 fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
663 use std::os::windows::fs::OpenOptionsExt;
664 let directory = tempfile::TempDir::new().expect("a directory");
665 let path = directory.path().join("record.json");
666 std::fs::write(&path, b"before").expect("a record");
667 let held = std::fs::OpenOptions::new()
668 .read(true)
669 .share_mode(0)
670 .open(&path)
671 .expect("the record held");
672 let release = std::thread::spawn(move || {
673 std::thread::sleep(Duration::from_millis(150));
674 drop(held);
675 });
676 super::replace_file(&path, b"after").expect("the record replaced");
677 release.join().expect("the handle let go");
678 assert_eq!(std::fs::read(&path).expect("the record"), b"after");
679 assert!(!path.with_extension("json.part").exists());
680 }
681
682 #[cfg(windows)]
683 #[test]
684 fn only_a_held_file_is_a_momentary_refusal_on_windows() {
685 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
686 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
687 assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
688 }
689
690 fn at(second: i64, z: f64) -> CheckedFrame {
692 CheckedFrame {
693 frame: format!("frame-{second}.jpg").into(),
694 captured_at: printobserver_types::Timestamp::from_unix_seconds(1_791_489_600 + second)
695 .expect("a time"),
696 print_z_mm: z,
697 }
698 }
699
700 fn heights(kept: &[CheckedFrame]) -> Vec<f64> {
702 kept.iter().map(|checked| checked.print_z_mm).collect()
703 }
704
705 #[test]
709 fn after_a_planned_change_growth_is_measured_from_frames_after_it() {
710 let state = tempfile::TempDir::new().expect("a state directory");
711 let store =
712 printobserver_store_sqlite::MemoryStore::new(state.path()).expect("an in-memory store");
713 let alignments = super::Alignments::new(state.path(), None, std::sync::Arc::new(store))
714 .expect("the verdicts' directories");
715 let print_id = printobserver_types::PrintId::new();
716 for (second, z) in [(0, 0.2), (60, 0.6)] {
717 alignments.record_checked_frame(print_id, at(second, z), 0.4);
718 }
719 let before = alignments.growth_reference(print_id, 1.0, 0.4);
720 assert_eq!(before.map(|checked| checked.print_z_mm), Some(0.6));
721
722 alignments.restart_growth(print_id);
723 assert_eq!(alignments.growth_reference(print_id, 1.0, 0.4), None);
724 alignments.record_checked_frame(print_id, at(3_000, 0.8), 0.4);
725 alignments.record_checked_frame(print_id, at(3_120, 1.4), 0.4);
726 let after = alignments.growth_reference(print_id, 1.4, 0.4);
727 assert_eq!(
728 after.map(|checked| checked.captured_at),
729 Some(at(3_000, 0.8).captured_at)
730 );
731 alignments.restart_growth(print_id);
733 alignments.restart_growth(print_id);
734 assert!(alignments.checked_frames(print_id).is_empty());
735 }
736
737 #[test]
738 fn a_check_measures_from_the_newest_frame_far_enough_below_it() {
739 let kept = [at(0, 0.2), at(60, 0.8), at(120, 2.0), at(180, 2.6)];
740 assert_eq!(
741 reference_in(&kept, 5.8, 3.0).map(|checked| checked.print_z_mm),
742 Some(2.6)
743 );
744 assert_eq!(
745 reference_in(&kept, 3.5, 3.0).map(|checked| checked.print_z_mm),
746 Some(0.2)
747 );
748 assert_eq!(reference_in(&kept, 3.1, 3.0), None, "none is 3 mm below");
749 }
750
751 #[test]
752 fn only_what_a_later_check_can_measure_from_is_kept() {
753 let mut kept = Vec::new();
754 for (second, z) in [(0, 0.2), (60, 0.8), (120, 2.0), (180, 3.4), (240, 4.0)] {
755 kept = kept_with(kept, at(second, z), 3.0);
756 }
757 assert_eq!(
758 heights(&kept),
759 [0.8, 2.0, 3.4, 4.0],
760 "0.2 is below 0.8, which is itself 3 mm below 4.0, so no later check needs it"
761 );
762 assert_eq!(
763 heights(&kept_with(kept, at(300, 1.0), 3.0)),
764 [1.0],
765 "a plan gone back down starts the record again"
766 );
767 }
768
769 #[test]
770 fn the_oldest_checked_frames_go_past_the_most_kept() {
771 let mut kept = Vec::new();
772 for second in 0..=i64::try_from(MAX_CHECKED_FRAMES).expect("a count") {
773 kept = kept_with(kept, at(second, 5.0), 3.0);
774 }
775 assert_eq!(kept.len(), MAX_CHECKED_FRAMES);
776 assert_eq!(kept[0].captured_at, at(1, 5.0).captured_at);
777 }
778}