use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use printobserver_core::PlanPosition;
use printobserver_core::store::PrintStore;
use printobserver_panels::{
AlignmentInputs, CameraCalibration, ComposeError, FirstLayerInputs, FirstLayerVerdict,
FrameField, InconclusiveReason, ReferenceLandmark, ViewCorrection, ViewJudgement, ViewOutcome,
judge_first_layer, judge_found, landmarks_in_frame,
};
use printobserver_supervisor_api::{ImageFallback, ImageKind};
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{EventBody, EventPayload, PrintId, Timestamp};
#[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,
#[serde(default)]
correction_px: [f64; 2],
},
Failed {
reason: AlignmentFailure,
},
}
impl Sample for PrintAlignment {
fn sample_full() -> Self {
Self::Passed {
offset_px: 14.6,
correction_px: [14.0, 4.0],
}
}
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,
view_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")
}
#[must_use]
pub fn camera_view_dir(state_dir: &Path) -> PathBuf {
state_dir.join("camera-view")
}
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)?;
let view_directory = camera_view_dir(state_dir);
std::fs::create_dir_all(&view_directory)?;
Ok(Self {
directory,
previous_directory,
checked_directory,
view_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;
}
match std::fs::read(self.path_of(print_id))
.ok()
.and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
{
Some(PrintAlignment::Failed {
reason: AlignmentFailure::Offset { .. },
})
| None => PrintAlignment::Pending,
Some(verdict) => verdict,
}
}
fn view_path_of(&self, print_id: PrintId) -> PathBuf {
self.view_directory.join(format!("{print_id}.json"))
}
fn view_state(&self, print_id: PrintId) -> CameraViewState {
std::fs::read(self.view_path_of(print_id))
.ok()
.and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
.unwrap_or_default()
}
fn keep_view_state(&self, print_id: PrintId, state: &CameraViewState) {
let Ok(bytes) = printobserver_types::serde_json::to_vec(state) else {
return;
};
if let Err(error) = replace_file(&self.view_path_of(print_id), &bytes) {
eprintln!(
"printobserver: print {print_id}: its camera view could not be recorded, so a later check reads the one before: {error}"
);
}
}
fn decide(&self, print_id: PrintId, verdict: &PrintAlignment) {
let Ok(bytes) = printobserver_types::serde_json::to_vec(verdict) else {
return;
};
match replace_file(&self.path_of(print_id), &bytes) {
Ok(()) => eprintln!(
"printobserver: print {print_id}: first-layer alignment {}",
said(verdict)
),
Err(error) => eprintln!(
"printobserver: print {print_id}: first-layer alignment {} could not be recorded: {error}",
said(verdict)
),
}
}
#[must_use]
pub fn correction_in_force(&self, print_id: PrintId) -> Option<ViewCorrection> {
let calibration = self.calibration.as_deref()?;
let PrintAlignment::Passed { correction_px, .. } = self.print_alignment(print_id) else {
return None;
};
Some(self.view_state(print_id).correction.unwrap_or_else(|| {
ViewCorrection::translation(
correction_px,
calibration
.landmarks
.iter()
.map(|landmark| ReferenceLandmark {
name: landmark.name.clone(),
offset_px: [0.0, 0.0],
score: 1.0,
})
.collect(),
)
}))
}
#[must_use]
pub fn inconclusive(&self, print_id: PrintId) -> Option<InconclusiveReason> {
self.view_state(print_id).inconclusive
}
#[must_use]
pub fn last_check_image(&self, print_id: PrintId) -> Option<LastCheckImage> {
self.view_state(print_id).last_check_image
}
#[must_use]
pub fn note_check_image(
&self,
print_id: PrintId,
shown: LastCheckImage,
frame_sha256: &str,
) -> Option<EventBody> {
let mut state = self.view_state(print_id);
let code = |image: &LastCheckImage| image.fallback.as_ref().map(|fallback| fallback.code);
let changed = state
.last_check_image
.as_ref()
.is_none_or(|last| last.kind != shown.kind || code(last) != code(&shown));
let notice = changed.then(|| {
body_of(&crate::judgements::CheckImageChangedPayload {
kind: shown.kind,
fallback: shown.fallback.clone(),
frame_sha256: frame_sha256.to_owned(),
})
});
state.last_check_image = Some(shown);
self.keep_view_state(print_id, &state);
notice.flatten()
}
#[must_use]
pub fn judge(&self, print_id: PrintId, judging: &Judging<'_>) -> Judged {
let Some(calibration) = self.calibration.as_deref() else {
return Judged::unjudged(PrintAlignment::Unavailable);
};
let mut judged = Judged::unjudged(self.print_alignment(print_id));
let mut state = self.view_state(print_id);
let in_force = self.correction_in_force(print_id);
let sha = judging.frame_sha256;
let landmarks = match landmarks_in_frame(
calibration,
judging.frame_jpeg,
judging.camera_snapshot_url,
) {
Ok(landmarks) => landmarks,
Err(error @ ComposeError::FrameMismatch { .. }) => {
let reason = error.to_string();
judged
.records
.extend(body_of(&crate::judgements::CameraViewJudgedPayload {
frame_sha256: sha.to_owned(),
outcome: ViewOutcome::FrameMismatch,
view_correction: in_force.clone(),
reason: Some(reason.clone()),
}));
if Self::alignment_due(&judged.alignment, judging).is_some() {
let failure = failure_of(&error, calibration);
judged.records.extend(body_of(
&crate::judgements::FirstLayerAlignmentJudgedPayload {
verdict: crate::judgements::AlignmentJudgedVerdict::Failed,
offset_px: None,
correction_px: None,
match_strength: None,
reason: failure_sentence(&failure),
frame_sha256: sha.to_owned(),
view_correction: in_force.clone(),
},
));
judged.alignment = PrintAlignment::Failed { reason: failure };
self.decide(print_id, &judged.alignment);
state.correction = None;
state.inconclusive = None;
self.keep_view_state(print_id, &state);
}
judged.correction = in_force.filter(|_| judged.alignment.passed());
judged.mismatch = Some(reason);
return judged;
}
Err(error) => {
judged.unreadable = Some(error.to_string());
return judged;
}
};
if judging.alignment != AlignmentJudging::Never
&& judged.alignment == PrintAlignment::Pending
&& judging
.plan
.is_some_and(|plan| plan.index.first_object_layer().is_none())
{
judged.alignment = PrintAlignment::Unavailable;
self.decide(print_id, &judged.alignment);
}
let due = Self::alignment_due(&judged.alignment, judging);
let view = match (due, &judged.alignment) {
(None, PrintAlignment::Passed { .. }) => {
let view = judge_found(calibration, landmarks, in_force.as_ref());
if view.outcome == ViewOutcome::ViewRefitRejected {
judged.alignment = PrintAlignment::Pending;
self.decide(print_id, &judged.alignment);
state.correction = None;
state.inconclusive = None;
self.keep_view_state(print_id, &state);
judged.rejected.clone_from(&view.reason);
} else {
judged.correction.clone_from(&in_force);
}
judged
.records
.extend(view_record(sha, &view, in_force.clone()));
view
}
(Some(first), _) => self.judge_alignment(
print_id,
calibration,
landmarks,
&first,
judging,
in_force,
&mut state,
&mut judged,
),
(None, _) => {
let view = judge_found(calibration, landmarks, None);
judged.records.extend(view_record(sha, &view, None));
view
}
};
judged.inconclusive = state.inconclusive;
judged.view = Some((view.outcome, view.reason));
judged
}
#[expect(
clippy::too_many_arguments,
reason = "the one judgement's inputs and the two records it updates"
)]
fn judge_alignment(
&self,
print_id: PrintId,
calibration: &CameraCalibration,
landmarks: Vec<printobserver_panels::FoundLandmark>,
first: &DueAlignment,
judging: &Judging<'_>,
in_force: Option<ViewCorrection>,
state: &mut CameraViewState,
judged: &mut Judged,
) -> ViewJudgement {
let sha = judging.frame_sha256;
let uncorrected = judge_found(calibration, landmarks.clone(), None);
let judgement = judge_first_layer(&FirstLayerInputs {
alignment: AlignmentInputs {
frame_jpeg: judging.frame_jpeg,
camera_snapshot_url: judging.camera_snapshot_url,
first_layer: &first.first_layer,
print_z_mm: first.print_z_mm,
calibration,
},
nozzle_xy_mm: first.nozzle_xy_mm,
});
let Ok(judgement) = judgement else {
judged.records.extend(view_record(sha, &uncorrected, None));
return uncorrected;
};
let found = judgement.found;
let (verdict, correction_px, reason) = match judgement.verdict {
FirstLayerVerdict::Passed => (
crate::judgements::AlignmentJudgedVerdict::Passed,
found.map(|found| {
printobserver_panels::alignment::correction_shift(
&found,
&first.first_layer,
first.print_z_mm,
)
}),
"clearly_found".to_owned(),
),
FirstLayerVerdict::Inconclusive(why) => (
crate::judgements::AlignmentJudgedVerdict::Inconclusive,
None,
why.as_str().to_owned(),
),
};
judged.records.extend(body_of(
&crate::judgements::FirstLayerAlignmentJudgedPayload {
verdict,
offset_px: found.map(|found| found.offset_px),
correction_px,
match_strength: found.map(|found| found.match_strength),
reason,
frame_sha256: sha.to_owned(),
view_correction: in_force,
},
));
match (judgement.verdict, found) {
(FirstLayerVerdict::Passed, Some(found)) => {
let shift = printobserver_panels::alignment::correction_shift(
&found,
&first.first_layer,
first.print_z_mm,
);
eprintln!(
"printobserver: print {print_id}: the first layer was found shifted [{:.0}, {:.0}] px at Z {:.2}, at a contrast of {:.1}; corrected by [{:.0}, {:.0}] px",
found.shift_px[0],
found.shift_px[1],
first.print_z_mm,
found.match_strength,
shift[0],
shift[1]
);
let correction = ViewCorrection::translation(shift, uncorrected.agreeing());
judged.alignment = PrintAlignment::Passed {
offset_px: found.offset_px,
correction_px: shift,
};
self.decide(print_id, &judged.alignment);
state.correction = Some(correction.clone());
state.inconclusive = None;
self.keep_view_state(print_id, state);
if uncorrected.moved(calibration) {
judged
.records
.extend(body_of(&crate::judgements::CameraViewRefitPayload {
frame_sha256: sha.to_owned(),
view_correction: correction.clone(),
}));
}
let view = judge_found(calibration, landmarks, Some(&correction));
judged
.records
.extend(view_record(sha, &view, Some(correction.clone())));
judged.correction = Some(correction);
view
}
(FirstLayerVerdict::Inconclusive(why), _) => {
judged.alignment = PrintAlignment::Pending;
self.decide(print_id, &judged.alignment);
state.correction = None;
state.inconclusive = Some(why);
self.keep_view_state(print_id, state);
judged.records.extend(view_record(sha, &uncorrected, None));
uncorrected
}
(FirstLayerVerdict::Passed, None) => {
judged.records.extend(view_record(sha, &uncorrected, None));
uncorrected
}
}
}
fn alignment_due(alignment: &PrintAlignment, judging: &Judging<'_>) -> Option<DueAlignment> {
let asked = match judging.alignment {
AlignmentJudging::Never => false,
AlignmentJudging::WhilePending => *alignment == PrintAlignment::Pending,
AlignmentJudging::Afresh => true,
};
if !asked {
return None;
}
let plan = judging.plan?;
let index = &plan.index;
let position = plan.file_position_bytes;
let (first, ends) = index.first_object_layer()?;
if position <= ends {
return None;
}
Some(DueAlignment {
first_layer: index.layer_toolpath(first).ok()?,
print_z_mm: index
.layer_at(position)
.and_then(|layer| index.layer_z_mm(layer))?,
nozzle_xy_mm: index.planned_head_at(position).ok().flatten(),
})
}
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,
&self.view_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,
correction_px,
} => format!(
"passed, offset {offset_px:.1} px, corrected by [{:.0}, {:.0}] px",
correction_px[0], correction_px[1]
),
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(),
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
struct CameraViewState {
#[serde(default)]
correction: Option<ViewCorrection>,
#[serde(default)]
inconclusive: Option<InconclusiveReason>,
#[serde(default)]
last_check_image: Option<LastCheckImage>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct LastCheckImage {
pub at: Timestamp,
pub kind: ImageKind,
pub fallback: Option<ImageFallback>,
}
impl Sample for LastCheckImage {
fn sample_full() -> Self {
Self {
at: Timestamp::sample_full(),
kind: ImageKind::WholeFrame,
fallback: Some(ImageFallback::sample_full()),
}
}
fn sample_minimal() -> Self {
Self {
at: Timestamp::sample_full(),
kind: ImageKind::ThreePanel,
fallback: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlignmentJudging {
Never,
WhilePending,
Afresh,
}
#[derive(Debug, Clone, Copy)]
pub struct Judging<'a> {
pub frame_jpeg: &'a [u8],
pub frame_sha256: &'a str,
pub camera_snapshot_url: &'a str,
pub plan: Option<&'a PlanPosition>,
pub alignment: AlignmentJudging,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Judged {
pub records: Vec<EventBody>,
pub alignment: PrintAlignment,
pub correction: Option<ViewCorrection>,
pub view: Option<(ViewOutcome, Option<String>)>,
pub rejected: Option<String>,
pub mismatch: Option<String>,
pub unreadable: Option<String>,
pub inconclusive: Option<InconclusiveReason>,
}
impl Judged {
#[must_use]
pub fn nothing_to_judge(alignment: PrintAlignment, kept_with: Option<EventBody>) -> Self {
Self {
records: kept_with.into_iter().collect(),
..Self::unjudged(alignment)
}
}
const fn unjudged(alignment: PrintAlignment) -> Self {
Self {
records: Vec::new(),
alignment,
correction: None,
view: None,
rejected: None,
mismatch: None,
unreadable: None,
inconclusive: None,
}
}
}
impl PrintAlignment {
#[must_use]
pub const fn passed(&self) -> bool {
matches!(self, Self::Passed { .. })
}
}
struct DueAlignment {
first_layer: printobserver_core::LayerToolpath,
print_z_mm: f64,
nozzle_xy_mm: Option<[f64; 2]>,
}
fn body_of<P: EventPayload>(payload: &P) -> Option<EventBody> {
EventBody::of(payload).ok()
}
fn view_record(
frame_sha256: &str,
view: &ViewJudgement,
view_correction: Option<ViewCorrection>,
) -> Option<EventBody> {
let reason = if view.outcome == ViewOutcome::Refit {
Some(crate::check_images::CALIBRATION_STALE.to_owned())
} else {
view.reason.clone()
};
body_of(&crate::judgements::CameraViewJudgedPayload {
frame_sha256: frame_sha256.to_owned(),
outcome: view.outcome,
view_correction,
reason,
})
}
fn failure_of(error: &ComposeError, calibration: &CameraCalibration) -> AlignmentFailure {
match error {
ComposeError::FrameMismatch {
field: FrameField::Resolution,
got,
..
} => AlignmentFailure::Resolution {
expected: calibration.image_size_px,
got: size_of(got),
},
_ => AlignmentFailure::Stream,
}
}
#[must_use]
pub fn failure_sentence(failure: &AlignmentFailure) -> String {
match failure {
AlignmentFailure::Offset { offset_px } => format!(
"the printed first layer lies {offset_px:.1} px from where the calibration projects it"
),
AlignmentFailure::Resolution { expected, got } => format!(
"the camera's frames are {}x{} and the calibration's {}x{}",
got[0], got[1], expected[0], expected[1]
),
AlignmentFailure::Stream => {
"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);
}
}