use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use printobserver_core::store::PrintStore;
use printobserver_core::{ActiveJob, Supervisor};
use printobserver_panels::alignment::SEARCH_PX;
use printobserver_panels::{
AlignmentInputs, CameraCalibration, ComposeError, FrameField, verify_first_layer_alignment,
};
use printobserver_types::PrintId;
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
tag = "failure",
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub enum AlignmentFailure {
Offset {
offset_px: f64,
},
Resolution {
expected: [u32; 2],
got: [u32; 2],
},
Stream,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
tag = "verdict",
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub enum PrintAlignment {
Unavailable,
Pending,
Passed {
offset_px: f64,
},
Failed {
reason: AlignmentFailure,
},
}
impl Sample for PrintAlignment {
fn sample_full() -> Self {
Self::Passed { offset_px: 14.5 }
}
fn sample_minimal() -> Self {
Self::Pending
}
fn sample_alternates() -> Vec<Self> {
vec![
Self::Unavailable,
Self::Failed {
reason: AlignmentFailure::Offset { offset_px: 48.5 },
},
Self::Failed {
reason: AlignmentFailure::Resolution {
expected: [1920, 1080],
got: [1280, 720],
},
},
Self::Failed {
reason: AlignmentFailure::Stream,
},
]
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct PreviousCheck {
pub frame: PathBuf,
pub captured_at: printobserver_types::Timestamp,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct CheckedFrame {
pub frame: PathBuf,
pub captured_at: printobserver_types::Timestamp,
pub print_z_mm: f64,
}
const MAX_CHECKED_FRAMES: usize = 512;
pub struct Alignments {
directory: PathBuf,
previous_directory: PathBuf,
checked_directory: PathBuf,
calibration: Option<Arc<CameraCalibration>>,
prints: Arc<dyn PrintStore>,
}
impl core::fmt::Debug for Alignments {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter
.debug_struct("Alignments")
.field("directory", &self.directory)
.field("calibrated", &self.calibration.is_some())
.finish_non_exhaustive()
}
}
#[must_use]
pub fn verdict_dir(state_dir: &Path) -> PathBuf {
state_dir.join("alignment")
}
#[must_use]
pub fn previous_check_dir(state_dir: &Path) -> PathBuf {
state_dir.join("previous-check")
}
#[must_use]
pub fn checked_frames_dir(state_dir: &Path) -> PathBuf {
state_dir.join("checked-frames")
}
impl Alignments {
pub fn new(
state_dir: &Path,
calibration: Option<Arc<CameraCalibration>>,
prints: Arc<dyn PrintStore>,
) -> std::io::Result<Self> {
let directory = verdict_dir(state_dir);
std::fs::create_dir_all(&directory)?;
let previous_directory = previous_check_dir(state_dir);
std::fs::create_dir_all(&previous_directory)?;
let checked_directory = checked_frames_dir(state_dir);
std::fs::create_dir_all(&checked_directory)?;
Ok(Self {
directory,
previous_directory,
checked_directory,
calibration,
prints,
})
}
fn path_of(&self, print_id: PrintId) -> PathBuf {
self.directory.join(format!("{print_id}.json"))
}
#[must_use]
pub fn calibration(&self) -> Option<&CameraCalibration> {
self.calibration.as_deref()
}
fn previous_path_of(&self, print_id: PrintId) -> PathBuf {
self.previous_directory.join(format!("{print_id}.json"))
}
#[must_use]
pub fn previous_check(&self, print_id: PrintId) -> Option<PreviousCheck> {
std::fs::read(self.previous_path_of(print_id))
.ok()
.and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
}
pub fn record_check(&self, print_id: PrintId, check: &PreviousCheck) {
let Ok(bytes) = printobserver_types::serde_json::to_vec(check) else {
return;
};
if let Err(error) = replace_file(&self.previous_path_of(print_id), &bytes) {
eprintln!(
"printobserver: print {print_id}: the last check's frame could not be recorded, so the next check shows an older one or none: {error}"
);
}
}
fn checked_path_of(&self, print_id: PrintId) -> PathBuf {
self.checked_directory.join(format!("{print_id}.json"))
}
#[must_use]
pub fn checked_frames(&self, print_id: PrintId) -> Vec<CheckedFrame> {
std::fs::read(self.checked_path_of(print_id))
.ok()
.and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
.unwrap_or_default()
}
pub fn restart_growth(&self, print_id: PrintId) {
let path = self.checked_path_of(print_id);
if let Err(error) = std::fs::remove_file(&path)
&& error.kind() != std::io::ErrorKind::NotFound
{
eprintln!(
"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}"
);
}
}
#[must_use]
pub fn growth_reference(
&self,
print_id: PrintId,
print_z_mm: f64,
rise_mm: f64,
) -> Option<CheckedFrame> {
reference_in(&self.checked_frames(print_id), print_z_mm, rise_mm).cloned()
}
pub fn record_checked_frame(&self, print_id: PrintId, checked: CheckedFrame, rise_mm: f64) {
let kept = kept_with(self.checked_frames(print_id), checked, rise_mm);
let Ok(bytes) = printobserver_types::serde_json::to_vec(&kept) else {
return;
};
if let Err(error) = replace_file(&self.checked_path_of(print_id), &bytes) {
eprintln!(
"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}"
);
}
}
#[must_use]
pub fn print_alignment(&self, print_id: PrintId) -> PrintAlignment {
if self.calibration.is_none() {
return PrintAlignment::Unavailable;
}
std::fs::read(self.path_of(print_id))
.ok()
.and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
.unwrap_or(PrintAlignment::Pending)
}
pub async fn check(
&self,
supervisor: &Supervisor,
active: ActiveJob,
) -> Option<PrintAlignment> {
let calibration = self.calibration.as_ref()?;
if self.print_alignment(active.print_id) != PrintAlignment::Pending {
return None;
}
let position = u64::try_from(active.file_position_bytes?).ok()?;
let index = supervisor.print_gcode_index(active.print_id).await?;
let Some((first, ends)) = index.first_object_layer() else {
return self.decide(active.print_id, PrintAlignment::Unavailable);
};
if position <= ends {
return None;
}
let first_layer = index.layer_toolpath(first).ok()?;
let print_z_mm = index
.layer_at(position)
.and_then(|layer| index.layer_z_mm(layer))?;
let (url, frame) = supervisor.fetch_camera_frame(active.print_id).await?;
let verdict = match verify_first_layer_alignment(&AlignmentInputs {
frame_jpeg: &frame,
camera_snapshot_url: &url,
first_layer: &first_layer,
print_z_mm,
calibration,
}) {
Ok(found) if found.passed => PrintAlignment::Passed {
offset_px: found.offset_px,
},
Ok(found) => PrintAlignment::Failed {
reason: AlignmentFailure::Offset {
offset_px: found.offset_px,
},
},
Err(ComposeError::FrameMismatch {
field: FrameField::Resolution,
got,
..
}) => PrintAlignment::Failed {
reason: AlignmentFailure::Resolution {
expected: calibration.image_size_px,
got: size_of(&got),
},
},
Err(ComposeError::FrameMismatch {
field: FrameField::Stream,
..
}) => PrintAlignment::Failed {
reason: AlignmentFailure::Stream,
},
Err(ComposeError::OutlineOffFrame) => PrintAlignment::Failed {
reason: AlignmentFailure::Offset {
offset_px: f64::from(SEARCH_PX),
},
},
Err(_) => return None,
};
self.decide(active.print_id, verdict)
}
fn decide(&self, print_id: PrintId, verdict: PrintAlignment) -> Option<PrintAlignment> {
let bytes = printobserver_types::serde_json::to_vec(&verdict).ok()?;
replace_file(&self.path_of(print_id), &bytes).ok()?;
eprintln!(
"printobserver: print {print_id}: first-layer alignment {}",
said(&verdict)
);
Some(verdict)
}
pub async fn sweep(&self) {
let Ok(open) = self.prints.open_prints().await else {
return;
};
let open: Vec<String> = open
.iter()
.flat_map(|print| {
[
format!("{}.json", print.id),
format!("{}.json.part", print.id),
]
})
.collect();
for directory in [
&self.directory,
&self.previous_directory,
&self.checked_directory,
] {
let Ok(entries) = std::fs::read_dir(directory) else {
continue;
};
for entry in entries.flatten() {
let name = entry.file_name();
if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
let _ = std::fs::remove_file(entry.path());
}
}
}
}
}
fn reference_in(kept: &[CheckedFrame], print_z_mm: f64, rise_mm: f64) -> Option<&CheckedFrame> {
kept.iter()
.rev()
.find(|checked| checked.print_z_mm <= print_z_mm - rise_mm)
}
fn kept_with(
mut kept: Vec<CheckedFrame>,
checked: CheckedFrame,
rise_mm: f64,
) -> Vec<CheckedFrame> {
if kept
.last()
.is_some_and(|last| checked.print_z_mm < last.print_z_mm)
{
kept.clear();
}
if let Some(reference) = kept
.iter()
.rposition(|earlier| earlier.print_z_mm <= checked.print_z_mm - rise_mm)
{
kept.drain(..reference);
}
kept.push(checked);
if kept.len() > MAX_CHECKED_FRAMES {
kept.drain(..kept.len() - MAX_CHECKED_FRAMES);
}
kept
}
const REPLACE_ATTEMPTS: u32 = 20;
const REPLACE_PAUSE: Duration = Duration::from_millis(25);
fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
let held = path.with_extension("json.part");
attempt_while_refused(
|| {
std::fs::write(&held, bytes)?;
std::fs::rename(&held, path)
},
refused_for_a_moment,
REPLACE_ATTEMPTS,
REPLACE_PAUSE,
)
.inspect_err(|_| {
let _ = std::fs::remove_file(&held);
})
}
fn attempt_while_refused(
mut attempt: impl FnMut() -> std::io::Result<()>,
refused: impl Fn(&std::io::Error) -> bool,
attempts: u32,
pause: Duration,
) -> std::io::Result<()> {
let mut made = 1;
loop {
match attempt() {
Err(error) if made < attempts && refused(&error) => {
std::thread::sleep(pause);
made += 1;
}
answered => return answered,
}
}
}
#[cfg(windows)]
fn refused_for_a_moment(error: &std::io::Error) -> bool {
matches!(error.raw_os_error(), Some(5 | 32))
}
#[cfg(not(windows))]
fn refused_for_a_moment(_error: &std::io::Error) -> bool {
false
}
fn size_of(text: &str) -> [u32; 2] {
let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
[parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
}
fn said(verdict: &PrintAlignment) -> String {
match verdict {
PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
PrintAlignment::Pending => "pending".to_owned(),
PrintAlignment::Passed { offset_px } => format!("passed, offset {offset_px:.1} px"),
PrintAlignment::Failed {
reason: AlignmentFailure::Offset { offset_px },
} => format!("failed, offset {offset_px:.1} px"),
PrintAlignment::Failed {
reason: AlignmentFailure::Resolution { expected, got },
} => format!(
"failed: the camera's frames are {}x{}, the calibration's {}x{}",
got[0], got[1], expected[0], expected[1]
),
PrintAlignment::Failed {
reason: AlignmentFailure::Stream,
} => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::{CheckedFrame, MAX_CHECKED_FRAMES, attempt_while_refused, kept_with, reference_in};
use std::cell::Cell;
use std::io::{Error, ErrorKind};
use std::time::Duration;
fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
move || {
made.set(made.get() + 1);
if made.get() <= refusals {
Err(Error::from(ErrorKind::PermissionDenied))
} else {
Ok(())
}
}
}
#[test]
fn a_momentary_refusal_is_attempted_again_until_it_passes() {
let made = Cell::new(0);
let answered =
attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
assert!(answered.is_ok(), "{answered:?}");
assert_eq!(made.get(), 3);
}
#[test]
fn a_refusal_that_outlasts_every_attempt_is_answered() {
let made = Cell::new(0);
let answered =
attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
assert_eq!(
answered.map_err(|error| error.kind()),
Err(ErrorKind::PermissionDenied)
);
assert_eq!(made.get(), 4);
}
#[test]
fn a_refusal_that_is_not_momentary_is_answered_at_once() {
let made = Cell::new(0);
let answered =
attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
assert!(answered.is_err());
assert_eq!(made.get(), 1);
}
#[cfg(windows)]
#[test]
fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
use std::os::windows::fs::OpenOptionsExt;
let directory = tempfile::TempDir::new().expect("a directory");
let path = directory.path().join("record.json");
std::fs::write(&path, b"before").expect("a record");
let held = std::fs::OpenOptions::new()
.read(true)
.share_mode(0)
.open(&path)
.expect("the record held");
let release = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(150));
drop(held);
});
super::replace_file(&path, b"after").expect("the record replaced");
release.join().expect("the handle let go");
assert_eq!(std::fs::read(&path).expect("the record"), b"after");
assert!(!path.with_extension("json.part").exists());
}
#[cfg(windows)]
#[test]
fn only_a_held_file_is_a_momentary_refusal_on_windows() {
assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
}
fn at(second: i64, z: f64) -> CheckedFrame {
CheckedFrame {
frame: format!("frame-{second}.jpg").into(),
captured_at: printobserver_types::Timestamp::from_unix_seconds(1_791_489_600 + second)
.expect("a time"),
print_z_mm: z,
}
}
fn heights(kept: &[CheckedFrame]) -> Vec<f64> {
kept.iter().map(|checked| checked.print_z_mm).collect()
}
#[test]
fn after_a_planned_change_growth_is_measured_from_frames_after_it() {
let state = tempfile::TempDir::new().expect("a state directory");
let store =
printobserver_store_sqlite::MemoryStore::new(state.path()).expect("an in-memory store");
let alignments = super::Alignments::new(state.path(), None, std::sync::Arc::new(store))
.expect("the verdicts' directories");
let print_id = printobserver_types::PrintId::new();
for (second, z) in [(0, 0.2), (60, 0.6)] {
alignments.record_checked_frame(print_id, at(second, z), 0.4);
}
let before = alignments.growth_reference(print_id, 1.0, 0.4);
assert_eq!(before.map(|checked| checked.print_z_mm), Some(0.6));
alignments.restart_growth(print_id);
assert_eq!(alignments.growth_reference(print_id, 1.0, 0.4), None);
alignments.record_checked_frame(print_id, at(3_000, 0.8), 0.4);
alignments.record_checked_frame(print_id, at(3_120, 1.4), 0.4);
let after = alignments.growth_reference(print_id, 1.4, 0.4);
assert_eq!(
after.map(|checked| checked.captured_at),
Some(at(3_000, 0.8).captured_at)
);
alignments.restart_growth(print_id);
alignments.restart_growth(print_id);
assert!(alignments.checked_frames(print_id).is_empty());
}
#[test]
fn a_check_measures_from_the_newest_frame_far_enough_below_it() {
let kept = [at(0, 0.2), at(60, 0.8), at(120, 2.0), at(180, 2.6)];
assert_eq!(
reference_in(&kept, 5.8, 3.0).map(|checked| checked.print_z_mm),
Some(2.6)
);
assert_eq!(
reference_in(&kept, 3.5, 3.0).map(|checked| checked.print_z_mm),
Some(0.2)
);
assert_eq!(reference_in(&kept, 3.1, 3.0), None, "none is 3 mm below");
}
#[test]
fn only_what_a_later_check_can_measure_from_is_kept() {
let mut kept = Vec::new();
for (second, z) in [(0, 0.2), (60, 0.8), (120, 2.0), (180, 3.4), (240, 4.0)] {
kept = kept_with(kept, at(second, z), 3.0);
}
assert_eq!(
heights(&kept),
[0.8, 2.0, 3.4, 4.0],
"0.2 is below 0.8, which is itself 3 mm below 4.0, so no later check needs it"
);
assert_eq!(
heights(&kept_with(kept, at(300, 1.0), 3.0)),
[1.0],
"a plan gone back down starts the record again"
);
}
#[test]
fn the_oldest_checked_frames_go_past_the_most_kept() {
let mut kept = Vec::new();
for second in 0..=i64::try_from(MAX_CHECKED_FRAMES).expect("a count") {
kept = kept_with(kept, at(second, 5.0), 3.0);
}
assert_eq!(kept.len(), MAX_CHECKED_FRAMES);
assert_eq!(kept[0].captured_at, at(1, 5.0).captured_at);
}
}