1use std::path::{Path, PathBuf};
23use std::sync::Arc;
24use std::time::Duration;
25
26use printobserver_core::store::PrintStore;
27use printobserver_core::{ActiveJob, Supervisor};
28use printobserver_panels::alignment::SEARCH_PX;
29use printobserver_panels::{
30 AlignmentInputs, CameraCalibration, ComposeError, FrameField, verify_first_layer_alignment,
31};
32use printobserver_types::PrintId;
33use printobserver_types::contract::Sample;
34use printobserver_types::schemars::JsonSchema;
35use printobserver_types::serde::{Deserialize, Serialize};
36
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
39#[serde(
40 crate = "printobserver_types::serde",
41 tag = "failure",
42 rename_all = "snake_case"
43)]
44#[schemars(crate = "printobserver_types::schemars")]
45pub enum AlignmentFailure {
46 Offset {
49 offset_px: f64,
51 },
52 Resolution {
54 expected: [u32; 2],
56 got: [u32; 2],
58 },
59 Stream,
61}
62
63#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
66#[serde(
67 crate = "printobserver_types::serde",
68 tag = "verdict",
69 rename_all = "snake_case"
70)]
71#[schemars(crate = "printobserver_types::schemars")]
72pub enum PrintAlignment {
73 Unavailable,
76 Pending,
79 Passed {
81 offset_px: f64,
83 },
84 Failed {
86 reason: AlignmentFailure,
88 },
89}
90
91impl Sample for PrintAlignment {
92 fn sample_full() -> Self {
93 Self::Passed { offset_px: 14.5 }
94 }
95
96 fn sample_minimal() -> Self {
97 Self::Pending
98 }
99
100 fn sample_alternates() -> Vec<Self> {
101 vec![
102 Self::Unavailable,
103 Self::Failed {
104 reason: AlignmentFailure::Offset { offset_px: 48.5 },
105 },
106 Self::Failed {
107 reason: AlignmentFailure::Resolution {
108 expected: [1920, 1080],
109 got: [1280, 720],
110 },
111 },
112 Self::Failed {
113 reason: AlignmentFailure::Stream,
114 },
115 ]
116 }
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(crate = "printobserver_types::serde")]
122pub struct PreviousCheck {
123 pub frame: PathBuf,
125 pub captured_at: printobserver_types::Timestamp,
127}
128
129pub struct Alignments {
132 directory: PathBuf,
134 previous_directory: PathBuf,
136 calibration: Option<Arc<CameraCalibration>>,
138 prints: Arc<dyn PrintStore>,
140}
141
142impl core::fmt::Debug for Alignments {
143 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
144 formatter
145 .debug_struct("Alignments")
146 .field("directory", &self.directory)
147 .field("calibrated", &self.calibration.is_some())
148 .finish_non_exhaustive()
149 }
150}
151
152#[must_use]
154pub fn verdict_dir(state_dir: &Path) -> PathBuf {
155 state_dir.join("alignment")
156}
157
158#[must_use]
161pub fn previous_check_dir(state_dir: &Path) -> PathBuf {
162 state_dir.join("previous-check")
163}
164
165impl Alignments {
166 pub fn new(
172 state_dir: &Path,
173 calibration: Option<Arc<CameraCalibration>>,
174 prints: Arc<dyn PrintStore>,
175 ) -> std::io::Result<Self> {
176 let directory = verdict_dir(state_dir);
177 std::fs::create_dir_all(&directory)?;
178 let previous_directory = previous_check_dir(state_dir);
179 std::fs::create_dir_all(&previous_directory)?;
180 Ok(Self {
181 directory,
182 previous_directory,
183 calibration,
184 prints,
185 })
186 }
187
188 fn path_of(&self, print_id: PrintId) -> PathBuf {
190 self.directory.join(format!("{print_id}.json"))
191 }
192
193 #[must_use]
195 pub fn calibration(&self) -> Option<&CameraCalibration> {
196 self.calibration.as_deref()
197 }
198
199 fn previous_path_of(&self, print_id: PrintId) -> PathBuf {
201 self.previous_directory.join(format!("{print_id}.json"))
202 }
203
204 #[must_use]
207 pub fn previous_check(&self, print_id: PrintId) -> Option<PreviousCheck> {
208 std::fs::read(self.previous_path_of(print_id))
209 .ok()
210 .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
211 }
212
213 pub fn record_check(&self, print_id: PrintId, check: &PreviousCheck) {
224 let Ok(bytes) = printobserver_types::serde_json::to_vec(check) else {
225 return;
226 };
227 if let Err(error) = replace_file(&self.previous_path_of(print_id), &bytes) {
228 eprintln!(
229 "printobserver: print {print_id}: the last check's frame could not be recorded, so the next check shows an older one or none: {error}"
230 );
231 }
232 }
233
234 #[must_use]
236 pub fn print_alignment(&self, print_id: PrintId) -> PrintAlignment {
237 if self.calibration.is_none() {
238 return PrintAlignment::Unavailable;
239 }
240 std::fs::read(self.path_of(print_id))
241 .ok()
242 .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
243 .unwrap_or(PrintAlignment::Pending)
244 }
245
246 pub async fn check(
250 &self,
251 supervisor: &Supervisor,
252 active: ActiveJob,
253 ) -> Option<PrintAlignment> {
254 let calibration = self.calibration.as_ref()?;
255 if self.print_alignment(active.print_id) != PrintAlignment::Pending {
258 return None;
259 }
260 let position = u64::try_from(active.file_position_bytes?).ok()?;
261 let index = supervisor.print_gcode_index(active.print_id).await?;
262 let Some((first, ends)) = index.first_object_layer() else {
263 return self.decide(active.print_id, PrintAlignment::Unavailable);
264 };
265 if position <= ends {
266 return None;
267 }
268 let first_layer = index.layer_toolpath(first).ok()?;
269 let print_z_mm = index
270 .layer_at(position)
271 .and_then(|layer| index.layer_z_mm(layer))?;
272 let (url, frame) = supervisor.fetch_camera_frame(active.print_id).await?;
273 let verdict = match verify_first_layer_alignment(&AlignmentInputs {
274 frame_jpeg: &frame,
275 camera_snapshot_url: &url,
276 first_layer: &first_layer,
277 print_z_mm,
278 calibration,
279 }) {
280 Ok(found) if found.passed => PrintAlignment::Passed {
281 offset_px: found.offset_px,
282 },
283 Ok(found) => PrintAlignment::Failed {
284 reason: AlignmentFailure::Offset {
285 offset_px: found.offset_px,
286 },
287 },
288 Err(ComposeError::FrameMismatch {
289 field: FrameField::Resolution,
290 got,
291 ..
292 }) => PrintAlignment::Failed {
293 reason: AlignmentFailure::Resolution {
294 expected: calibration.image_size_px,
295 got: size_of(&got),
296 },
297 },
298 Err(ComposeError::FrameMismatch {
299 field: FrameField::Stream,
300 ..
301 }) => PrintAlignment::Failed {
302 reason: AlignmentFailure::Stream,
303 },
304 Err(ComposeError::OutlineOffFrame) => PrintAlignment::Failed {
307 reason: AlignmentFailure::Offset {
308 offset_px: f64::from(SEARCH_PX),
309 },
310 },
311 Err(_) => return None,
312 };
313 self.decide(active.print_id, verdict)
314 }
315
316 fn decide(&self, print_id: PrintId, verdict: PrintAlignment) -> Option<PrintAlignment> {
323 let bytes = printobserver_types::serde_json::to_vec(&verdict).ok()?;
324 replace_file(&self.path_of(print_id), &bytes).ok()?;
325 eprintln!(
326 "printobserver: print {print_id}: first-layer alignment {}",
327 said(&verdict)
328 );
329 Some(verdict)
330 }
331
332 pub async fn sweep(&self) {
342 let Ok(open) = self.prints.open_prints().await else {
343 return;
344 };
345 let open: Vec<String> = open
346 .iter()
347 .map(|print| format!("{}.json", print.id))
348 .collect();
349 for directory in [&self.directory, &self.previous_directory] {
350 let Ok(entries) = std::fs::read_dir(directory) else {
351 continue;
352 };
353 for entry in entries.flatten() {
354 let name = entry.file_name();
355 if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
356 let _ = std::fs::remove_file(entry.path());
357 }
358 }
359 }
360 }
361}
362
363const REPLACE_ATTEMPTS: u32 = 20;
367const REPLACE_PAUSE: Duration = Duration::from_millis(25);
368
369fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
382 let held = path.with_extension("json.part");
383 attempt_while_refused(
384 || {
385 std::fs::write(&held, bytes)?;
386 std::fs::rename(&held, path)
387 },
388 refused_for_a_moment,
389 REPLACE_ATTEMPTS,
390 REPLACE_PAUSE,
391 )
392 .inspect_err(|_| {
393 let _ = std::fs::remove_file(&held);
394 })
395}
396
397fn attempt_while_refused(
400 mut attempt: impl FnMut() -> std::io::Result<()>,
401 refused: impl Fn(&std::io::Error) -> bool,
402 attempts: u32,
403 pause: Duration,
404) -> std::io::Result<()> {
405 let mut made = 1;
406 loop {
407 match attempt() {
408 Err(error) if made < attempts && refused(&error) => {
409 std::thread::sleep(pause);
410 made += 1;
411 }
412 answered => return answered,
413 }
414 }
415}
416
417#[cfg(windows)]
420fn refused_for_a_moment(error: &std::io::Error) -> bool {
421 matches!(error.raw_os_error(), Some(5 | 32))
422}
423
424#[cfg(not(windows))]
427fn refused_for_a_moment(_error: &std::io::Error) -> bool {
428 false
429}
430
431fn size_of(text: &str) -> [u32; 2] {
433 let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
434 [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
435}
436
437fn said(verdict: &PrintAlignment) -> String {
439 match verdict {
440 PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
441 PrintAlignment::Pending => "pending".to_owned(),
442 PrintAlignment::Passed { offset_px } => format!("passed, offset {offset_px:.1} px"),
443 PrintAlignment::Failed {
444 reason: AlignmentFailure::Offset { offset_px },
445 } => format!("failed, offset {offset_px:.1} px"),
446 PrintAlignment::Failed {
447 reason: AlignmentFailure::Resolution { expected, got },
448 } => format!(
449 "failed: the camera's frames are {}x{}, the calibration's {}x{}",
450 got[0], got[1], expected[0], expected[1]
451 ),
452 PrintAlignment::Failed {
453 reason: AlignmentFailure::Stream,
454 } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use super::attempt_while_refused;
461 use std::cell::Cell;
462 use std::io::{Error, ErrorKind};
463 use std::time::Duration;
464
465 fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
468 move || {
469 made.set(made.get() + 1);
470 if made.get() <= refusals {
471 Err(Error::from(ErrorKind::PermissionDenied))
472 } else {
473 Ok(())
474 }
475 }
476 }
477
478 #[test]
479 fn a_momentary_refusal_is_attempted_again_until_it_passes() {
480 let made = Cell::new(0);
481 let answered =
482 attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
483 assert!(answered.is_ok(), "{answered:?}");
484 assert_eq!(made.get(), 3);
485 }
486
487 #[test]
488 fn a_refusal_that_outlasts_every_attempt_is_answered() {
489 let made = Cell::new(0);
490 let answered =
491 attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
492 assert_eq!(
493 answered.map_err(|error| error.kind()),
494 Err(ErrorKind::PermissionDenied)
495 );
496 assert_eq!(made.get(), 4);
497 }
498
499 #[test]
500 fn a_refusal_that_is_not_momentary_is_answered_at_once() {
501 let made = Cell::new(0);
502 let answered =
503 attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
504 assert!(answered.is_err());
505 assert_eq!(made.get(), 1);
506 }
507
508 #[cfg(windows)]
512 #[test]
513 fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
514 use std::os::windows::fs::OpenOptionsExt;
515 let directory = tempfile::TempDir::new().expect("a directory");
516 let path = directory.path().join("record.json");
517 std::fs::write(&path, b"before").expect("a record");
518 let held = std::fs::OpenOptions::new()
519 .read(true)
520 .share_mode(0)
521 .open(&path)
522 .expect("the record held");
523 let release = std::thread::spawn(move || {
524 std::thread::sleep(Duration::from_millis(150));
525 drop(held);
526 });
527 super::replace_file(&path, b"after").expect("the record replaced");
528 release.join().expect("the handle let go");
529 assert_eq!(std::fs::read(&path).expect("the record"), b"after");
530 assert!(!path.with_extension("json.part").exists());
531 }
532
533 #[cfg(windows)]
534 #[test]
535 fn only_a_held_file_is_a_momentary_refusal_on_windows() {
536 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
537 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
538 assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
539 }
540}