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) {
348 let Ok(open) = self.prints.open_prints().await else {
349 return;
350 };
351 let open: Vec<String> = open
352 .iter()
353 .flat_map(|print| {
354 [
355 format!("{}.json", print.id),
356 format!("{}.json.part", print.id),
357 ]
358 })
359 .collect();
360 for directory in [&self.directory, &self.previous_directory] {
361 let Ok(entries) = std::fs::read_dir(directory) else {
362 continue;
363 };
364 for entry in entries.flatten() {
365 let name = entry.file_name();
366 if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
367 let _ = std::fs::remove_file(entry.path());
368 }
369 }
370 }
371 }
372}
373
374const REPLACE_ATTEMPTS: u32 = 20;
378const REPLACE_PAUSE: Duration = Duration::from_millis(25);
379
380fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
393 let held = path.with_extension("json.part");
394 attempt_while_refused(
395 || {
396 std::fs::write(&held, bytes)?;
397 std::fs::rename(&held, path)
398 },
399 refused_for_a_moment,
400 REPLACE_ATTEMPTS,
401 REPLACE_PAUSE,
402 )
403 .inspect_err(|_| {
404 let _ = std::fs::remove_file(&held);
405 })
406}
407
408fn attempt_while_refused(
411 mut attempt: impl FnMut() -> std::io::Result<()>,
412 refused: impl Fn(&std::io::Error) -> bool,
413 attempts: u32,
414 pause: Duration,
415) -> std::io::Result<()> {
416 let mut made = 1;
417 loop {
418 match attempt() {
419 Err(error) if made < attempts && refused(&error) => {
420 std::thread::sleep(pause);
421 made += 1;
422 }
423 answered => return answered,
424 }
425 }
426}
427
428#[cfg(windows)]
431fn refused_for_a_moment(error: &std::io::Error) -> bool {
432 matches!(error.raw_os_error(), Some(5 | 32))
433}
434
435#[cfg(not(windows))]
438fn refused_for_a_moment(_error: &std::io::Error) -> bool {
439 false
440}
441
442fn size_of(text: &str) -> [u32; 2] {
444 let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
445 [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
446}
447
448fn said(verdict: &PrintAlignment) -> String {
450 match verdict {
451 PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
452 PrintAlignment::Pending => "pending".to_owned(),
453 PrintAlignment::Passed { offset_px } => format!("passed, offset {offset_px:.1} px"),
454 PrintAlignment::Failed {
455 reason: AlignmentFailure::Offset { offset_px },
456 } => format!("failed, offset {offset_px:.1} px"),
457 PrintAlignment::Failed {
458 reason: AlignmentFailure::Resolution { expected, got },
459 } => format!(
460 "failed: the camera's frames are {}x{}, the calibration's {}x{}",
461 got[0], got[1], expected[0], expected[1]
462 ),
463 PrintAlignment::Failed {
464 reason: AlignmentFailure::Stream,
465 } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
466 }
467}
468
469#[cfg(test)]
470mod tests {
471 use super::attempt_while_refused;
472 use std::cell::Cell;
473 use std::io::{Error, ErrorKind};
474 use std::time::Duration;
475
476 fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
479 move || {
480 made.set(made.get() + 1);
481 if made.get() <= refusals {
482 Err(Error::from(ErrorKind::PermissionDenied))
483 } else {
484 Ok(())
485 }
486 }
487 }
488
489 #[test]
490 fn a_momentary_refusal_is_attempted_again_until_it_passes() {
491 let made = Cell::new(0);
492 let answered =
493 attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
494 assert!(answered.is_ok(), "{answered:?}");
495 assert_eq!(made.get(), 3);
496 }
497
498 #[test]
499 fn a_refusal_that_outlasts_every_attempt_is_answered() {
500 let made = Cell::new(0);
501 let answered =
502 attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
503 assert_eq!(
504 answered.map_err(|error| error.kind()),
505 Err(ErrorKind::PermissionDenied)
506 );
507 assert_eq!(made.get(), 4);
508 }
509
510 #[test]
511 fn a_refusal_that_is_not_momentary_is_answered_at_once() {
512 let made = Cell::new(0);
513 let answered =
514 attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
515 assert!(answered.is_err());
516 assert_eq!(made.get(), 1);
517 }
518
519 #[cfg(windows)]
523 #[test]
524 fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
525 use std::os::windows::fs::OpenOptionsExt;
526 let directory = tempfile::TempDir::new().expect("a directory");
527 let path = directory.path().join("record.json");
528 std::fs::write(&path, b"before").expect("a record");
529 let held = std::fs::OpenOptions::new()
530 .read(true)
531 .share_mode(0)
532 .open(&path)
533 .expect("the record held");
534 let release = std::thread::spawn(move || {
535 std::thread::sleep(Duration::from_millis(150));
536 drop(held);
537 });
538 super::replace_file(&path, b"after").expect("the record replaced");
539 release.join().expect("the handle let go");
540 assert_eq!(std::fs::read(&path).expect("the record"), b"after");
541 assert!(!path.with_extension("json.part").exists());
542 }
543
544 #[cfg(windows)]
545 #[test]
546 fn only_a_held_file_is_a_momentary_refusal_on_windows() {
547 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
548 assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
549 assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
550 }
551}