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 #[must_use]
286 pub fn growth_reference(
287 &self,
288 print_id: PrintId,
289 print_z_mm: f64,
290 rise_mm: f64,
291 ) -> Option<CheckedFrame> {
292 reference_in(&self.checked_frames(print_id), print_z_mm, rise_mm).cloned()
293 }
294
295 pub fn record_checked_frame(&self, print_id: PrintId, checked: CheckedFrame, rise_mm: f64) {
304 let kept = kept_with(self.checked_frames(print_id), checked, rise_mm);
305 let Ok(bytes) = printobserver_types::serde_json::to_vec(&kept) else {
306 return;
307 };
308 if let Err(error) = replace_file(&self.checked_path_of(print_id), &bytes) {
309 eprintln!(
310 "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}"
311 );
312 }
313 }
314
315 #[must_use]
317 pub fn print_alignment(&self, print_id: PrintId) -> PrintAlignment {
318 if self.calibration.is_none() {
319 return PrintAlignment::Unavailable;
320 }
321 std::fs::read(self.path_of(print_id))
322 .ok()
323 .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
324 .unwrap_or(PrintAlignment::Pending)
325 }
326
327 pub async fn check(
331 &self,
332 supervisor: &Supervisor,
333 active: ActiveJob,
334 ) -> Option<PrintAlignment> {
335 let calibration = self.calibration.as_ref()?;
336 if self.print_alignment(active.print_id) != PrintAlignment::Pending {
339 return None;
340 }
341 let position = u64::try_from(active.file_position_bytes?).ok()?;
342 let index = supervisor.print_gcode_index(active.print_id).await?;
343 let Some((first, ends)) = index.first_object_layer() else {
344 return self.decide(active.print_id, PrintAlignment::Unavailable);
345 };
346 if position <= ends {
347 return None;
348 }
349 let first_layer = index.layer_toolpath(first).ok()?;
350 let print_z_mm = index
351 .layer_at(position)
352 .and_then(|layer| index.layer_z_mm(layer))?;
353 let (url, frame) = supervisor.fetch_camera_frame(active.print_id).await?;
354 let verdict = match verify_first_layer_alignment(&AlignmentInputs {
355 frame_jpeg: &frame,
356 camera_snapshot_url: &url,
357 first_layer: &first_layer,
358 print_z_mm,
359 calibration,
360 }) {
361 Ok(found) if found.passed => PrintAlignment::Passed {
362 offset_px: found.offset_px,
363 },
364 Ok(found) => PrintAlignment::Failed {
365 reason: AlignmentFailure::Offset {
366 offset_px: found.offset_px,
367 },
368 },
369 Err(ComposeError::FrameMismatch {
370 field: FrameField::Resolution,
371 got,
372 ..
373 }) => PrintAlignment::Failed {
374 reason: AlignmentFailure::Resolution {
375 expected: calibration.image_size_px,
376 got: size_of(&got),
377 },
378 },
379 Err(ComposeError::FrameMismatch {
380 field: FrameField::Stream,
381 ..
382 }) => PrintAlignment::Failed {
383 reason: AlignmentFailure::Stream,
384 },
385 Err(ComposeError::OutlineOffFrame) => PrintAlignment::Failed {
388 reason: AlignmentFailure::Offset {
389 offset_px: f64::from(SEARCH_PX),
390 },
391 },
392 Err(_) => return None,
393 };
394 self.decide(active.print_id, verdict)
395 }
396
397 fn decide(&self, print_id: PrintId, verdict: PrintAlignment) -> Option<PrintAlignment> {
404 let bytes = printobserver_types::serde_json::to_vec(&verdict).ok()?;
405 replace_file(&self.path_of(print_id), &bytes).ok()?;
406 eprintln!(
407 "printobserver: print {print_id}: first-layer alignment {}",
408 said(&verdict)
409 );
410 Some(verdict)
411 }
412
413 pub async fn sweep(&self) {
429 let Ok(open) = self.prints.open_prints().await else {
430 return;
431 };
432 let open: Vec<String> = open
433 .iter()
434 .flat_map(|print| {
435 [
436 format!("{}.json", print.id),
437 format!("{}.json.part", print.id),
438 ]
439 })
440 .collect();
441 for directory in [
442 &self.directory,
443 &self.previous_directory,
444 &self.checked_directory,
445 ] {
446 let Ok(entries) = std::fs::read_dir(directory) else {
447 continue;
448 };
449 for entry in entries.flatten() {
450 let name = entry.file_name();
451 if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
452 let _ = std::fs::remove_file(entry.path());
453 }
454 }
455 }
456 }
457}
458
459fn reference_in(kept: &[CheckedFrame], print_z_mm: f64, rise_mm: f64) -> Option<&CheckedFrame> {
462 kept.iter()
463 .rev()
464 .find(|checked| checked.print_z_mm <= print_z_mm - rise_mm)
465}
466
467fn kept_with(
472 mut kept: Vec<CheckedFrame>,
473 checked: CheckedFrame,
474 rise_mm: f64,
475) -> Vec<CheckedFrame> {
476 if kept
477 .last()
478 .is_some_and(|last| checked.print_z_mm < last.print_z_mm)
479 {
480 kept.clear();
481 }
482 if let Some(reference) = kept
483 .iter()
484 .rposition(|earlier| earlier.print_z_mm <= checked.print_z_mm - rise_mm)
485 {
486 kept.drain(..reference);
487 }
488 kept.push(checked);
489 if kept.len() > MAX_CHECKED_FRAMES {
490 kept.drain(..kept.len() - MAX_CHECKED_FRAMES);
491 }
492 kept
493}
494
495const REPLACE_ATTEMPTS: u32 = 20;
499const REPLACE_PAUSE: Duration = Duration::from_millis(25);
500
501fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
514 let held = path.with_extension("json.part");
515 attempt_while_refused(
516 || {
517 std::fs::write(&held, bytes)?;
518 std::fs::rename(&held, path)
519 },
520 refused_for_a_moment,
521 REPLACE_ATTEMPTS,
522 REPLACE_PAUSE,
523 )
524 .inspect_err(|_| {
525 let _ = std::fs::remove_file(&held);
526 })
527}
528
529fn attempt_while_refused(
532 mut attempt: impl FnMut() -> std::io::Result<()>,
533 refused: impl Fn(&std::io::Error) -> bool,
534 attempts: u32,
535 pause: Duration,
536) -> std::io::Result<()> {
537 let mut made = 1;
538 loop {
539 match attempt() {
540 Err(error) if made < attempts && refused(&error) => {
541 std::thread::sleep(pause);
542 made += 1;
543 }
544 answered => return answered,
545 }
546 }
547}
548
549#[cfg(windows)]
552fn refused_for_a_moment(error: &std::io::Error) -> bool {
553 matches!(error.raw_os_error(), Some(5 | 32))
554}
555
556#[cfg(not(windows))]
559fn refused_for_a_moment(_error: &std::io::Error) -> bool {
560 false
561}
562
563fn size_of(text: &str) -> [u32; 2] {
565 let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
566 [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
567}
568
569fn said(verdict: &PrintAlignment) -> String {
571 match verdict {
572 PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
573 PrintAlignment::Pending => "pending".to_owned(),
574 PrintAlignment::Passed { offset_px } => format!("passed, offset {offset_px:.1} px"),
575 PrintAlignment::Failed {
576 reason: AlignmentFailure::Offset { offset_px },
577 } => format!("failed, offset {offset_px:.1} px"),
578 PrintAlignment::Failed {
579 reason: AlignmentFailure::Resolution { expected, got },
580 } => format!(
581 "failed: the camera's frames are {}x{}, the calibration's {}x{}",
582 got[0], got[1], expected[0], expected[1]
583 ),
584 PrintAlignment::Failed {
585 reason: AlignmentFailure::Stream,
586 } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
587 }
588}
589
590#[cfg(test)]
591mod tests {
592 use super::{CheckedFrame, MAX_CHECKED_FRAMES, attempt_while_refused, kept_with, reference_in};
593 use std::cell::Cell;
594 use std::io::{Error, ErrorKind};
595 use std::time::Duration;
596
597 fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
600 move || {
601 made.set(made.get() + 1);
602 if made.get() <= refusals {
603 Err(Error::from(ErrorKind::PermissionDenied))
604 } else {
605 Ok(())
606 }
607 }
608 }
609
610 #[test]
611 fn a_momentary_refusal_is_attempted_again_until_it_passes() {
612 let made = Cell::new(0);
613 let answered =
614 attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
615 assert!(answered.is_ok(), "{answered:?}");
616 assert_eq!(made.get(), 3);
617 }
618
619 #[test]
620 fn a_refusal_that_outlasts_every_attempt_is_answered() {
621 let made = Cell::new(0);
622 let answered =
623 attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
624 assert_eq!(
625 answered.map_err(|error| error.kind()),
626 Err(ErrorKind::PermissionDenied)
627 );
628 assert_eq!(made.get(), 4);
629 }
630
631 #[test]
632 fn a_refusal_that_is_not_momentary_is_answered_at_once() {
633 let made = Cell::new(0);
634 let answered =
635 attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
636 assert!(answered.is_err());
637 assert_eq!(made.get(), 1);
638 }
639
640 #[cfg(windows)]
644 #[test]
645 fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
646 use std::os::windows::fs::OpenOptionsExt;
647 let directory = tempfile::TempDir::new().expect("a directory");
648 let path = directory.path().join("record.json");
649 std::fs::write(&path, b"before").expect("a record");
650 let held = std::fs::OpenOptions::new()
651 .read(true)
652 .share_mode(0)
653 .open(&path)
654 .expect("the record held");
655 let release = std::thread::spawn(move || {
656 std::thread::sleep(Duration::from_millis(150));
657 drop(held);
658 });
659 super::replace_file(&path, b"after").expect("the record replaced");
660 release.join().expect("the handle let go");
661 assert_eq!(std::fs::read(&path).expect("the record"), b"after");
662 assert!(!path.with_extension("json.part").exists());
663 }
664
665 #[cfg(windows)]
666 #[test]
667 fn only_a_held_file_is_a_momentary_refusal_on_windows() {
668 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
669 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
670 assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
671 }
672
673 fn at(second: i64, z: f64) -> CheckedFrame {
675 CheckedFrame {
676 frame: format!("frame-{second}.jpg").into(),
677 captured_at: printobserver_types::Timestamp::from_unix_seconds(1_791_489_600 + second)
678 .expect("a time"),
679 print_z_mm: z,
680 }
681 }
682
683 fn heights(kept: &[CheckedFrame]) -> Vec<f64> {
685 kept.iter().map(|checked| checked.print_z_mm).collect()
686 }
687
688 #[test]
689 fn a_check_measures_from_the_newest_frame_far_enough_below_it() {
690 let kept = [at(0, 0.2), at(60, 0.8), at(120, 2.0), at(180, 2.6)];
691 assert_eq!(
692 reference_in(&kept, 5.8, 3.0).map(|checked| checked.print_z_mm),
693 Some(2.6)
694 );
695 assert_eq!(
696 reference_in(&kept, 3.5, 3.0).map(|checked| checked.print_z_mm),
697 Some(0.2)
698 );
699 assert_eq!(reference_in(&kept, 3.1, 3.0), None, "none is 3 mm below");
700 }
701
702 #[test]
703 fn only_what_a_later_check_can_measure_from_is_kept() {
704 let mut kept = Vec::new();
705 for (second, z) in [(0, 0.2), (60, 0.8), (120, 2.0), (180, 3.4), (240, 4.0)] {
706 kept = kept_with(kept, at(second, z), 3.0);
707 }
708 assert_eq!(
709 heights(&kept),
710 [0.8, 2.0, 3.4, 4.0],
711 "0.2 is below 0.8, which is itself 3 mm below 4.0, so no later check needs it"
712 );
713 assert_eq!(
714 heights(&kept_with(kept, at(300, 1.0), 3.0)),
715 [1.0],
716 "a plan gone back down starts the record again"
717 );
718 }
719
720 #[test]
721 fn the_oldest_checked_frames_go_past_the_most_kept() {
722 let mut kept = Vec::new();
723 for second in 0..=i64::try_from(MAX_CHECKED_FRAMES).expect("a count") {
724 kept = kept_with(kept, at(second, 5.0), 3.0);
725 }
726 assert_eq!(kept.len(), MAX_CHECKED_FRAMES);
727 assert_eq!(kept[0].captured_at, at(1, 5.0).captured_at);
728 }
729}