use core::time::Duration;
use std::path::PathBuf;
use printobserver_octoprint::standin::JobScript;
use printobserver_server::Running;
use printobserver_types::serde_json::{Value, json};
use printobserver_types::{PrintId, Timestamp};
use crate::camera_host::{Scripted, ScriptedHost};
use crate::composite_checks::{
Camera, FILE, Journey, block_under, calibration_at, expected_check, expected_composite, frame,
index_of, sha256, slice,
};
use crate::lean_checks::handed;
use crate::world::{OPERATOR, presenting};
const INSTALLER: &str = "scripts/install.sh";
const CASE: &str = "two-colour-box-2026-11-28";
const INTERVAL_S: i64 = 2;
const JUDGED: [(&str, u64); 3] = [
("070026-94b6cef20a02.jpg", 24_174),
("070721-f07bf91246a3.jpg", 39_844),
("070922-de189020b6f6.jpg", 51_973),
];
const LATER: u64 = 60_000;
fn calibration() -> Value {
calibration_named("core-one-2026-11-27.json")
}
fn calibration_named(name: &str) -> Value {
printobserver_types::serde_json::from_slice(
&std::fs::read(
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/real-prints/cameras")
.join(name),
)
.expect("the committed calibration"),
)
.expect("JSON")
}
fn box_slice() -> Vec<u8> {
uninterrupted(&slice("two-colour-box-2026-11-28.gcode"))
}
fn local_box_slice() -> Vec<u8> {
uninterrupted(&slice("two-colour-box-2026-11-28.local-slice.gcode"))
}
fn uninterrupted(slice: &[u8]) -> Vec<u8> {
slice
.split(|byte| *byte == b'\n')
.map(|line| {
if line == b"M600" || line == b"M600\r" {
line.iter()
.enumerate()
.map(|(at, byte)| if at == 0 { b';' } else { *byte })
.collect()
} else {
line.to_vec()
}
})
.collect::<Vec<_>>()
.join(&b'\n')
}
fn shifted(bytes: &[u8], by: usize) -> Vec<u8> {
let mut decoded = image::load_from_memory(bytes).expect("a frame").to_rgb8();
let width = decoded.width() as usize;
let raw: &mut [u8] = &mut decoded;
for line in raw.chunks_exact_mut(width * 3) {
let edge = [line[0], line[1], line[2]];
line.copy_within(..(width - by) * 3, by * 3);
for pixel in line[..by * 3].chunks_exact_mut(3) {
pixel.copy_from_slice(&edge);
}
}
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95)
.encode_image(&decoded)
.expect("a frame encodes");
out
}
fn job_at(journey: &Journey, position: u64) {
journey.at(position);
}
struct Checks<'a> {
journey: &'a Journey,
hold: PathBuf,
count: usize,
}
impl<'a> Checks<'a> {
fn holding(journey: &'a Journey) -> Self {
let hold = journey.root.path().join("hold");
std::fs::write(&hold, b"").expect("the hold is writable");
Self {
journey,
hold,
count: 0,
}
}
async fn next(&mut self, position: u64) -> Value {
job_at(self.journey, position);
if self.count > 0 {
std::fs::remove_file(&self.hold).expect("the hold is removable");
tokio::time::sleep(Duration::from_millis(400)).await;
std::fs::write(&self.hold, b"").expect("the hold is writable");
}
self.count += 1;
let seen = self.journey.runs(self.count).await;
seen[self.count - 1].clone()
}
fn release(self) {
let _ = std::fs::remove_file(&self.hold);
}
}
fn situation(seen: &Value) -> Value {
let (prompt, _) = handed(seen);
block_under(&prompt, "## The situation when this turn began")
}
fn captured_at(seen: &Value) -> Timestamp {
let (prompt, _) = handed(seen);
printobserver_types::serde_json::from_value(
block_under(&prompt, "## The event")["payload"]["frame_captured_at"].clone(),
)
.expect("the check's frame was captured at a time")
}
async fn checked(server: &Running, sheet: &str, z: f64) -> Value {
let response = presenting(OPERATOR)
.get(format!(
"{}/camera/check?sheet={sheet}&bed_z_mm={z}",
server.base_url()
))
.send()
.await
.expect("the server answers");
assert_eq!(response.status(), reqwest::StatusCode::OK);
response.json().await.expect("JSON")
}
async fn started_under(server: &Running, sheet: &str, camera_check: &Value) -> PrintId {
let path = printobserver_server::operation("start_print")
.expect("`start_print` is served")
.path
.replace("{print_id}", &PrintId::new().to_string());
let body = json!({
"file_name": FILE,
"manifest": {
"file_name": FILE,
"material": "PLA",
"nozzle_diameter_mm": 0.6,
"slicer_profile": "0.20mm STRUCTURAL",
"sheet": sheet,
"allowed": {},
"metadata": {},
"camera_check": camera_check,
},
"override_filament_check": true,
"override_material_check": true,
"override_sheet_check": true,
"reason": "the camera was checked on the empty sheet",
"actor": "operator",
});
let answer: Value = presenting(OPERATOR)
.post(format!("{}{path}", server.base_url()))
.json(&body)
.send()
.await
.expect("the server answers")
.json()
.await
.expect("JSON");
assert_eq!(answer["record"]["decision"], "accepted", "{answer:#}");
answer["record"]["print_id"]
.as_str()
.expect("a print")
.parse()
.expect("a print id")
}
async fn history(server: &Running, print_id: PrintId) -> Vec<Value> {
let body: Value = presenting(OPERATOR)
.get(format!(
"{}/prints/{print_id}/history?limit=1000",
server.base_url()
))
.send()
.await
.expect("the server answers")
.json()
.await
.expect("JSON");
let mut events = body["events"].as_array().expect("events").clone();
events.sort_by_key(|event| event["id"].as_str().unwrap_or_default().to_owned());
events
}
fn payloads(events: &[Value], kind: &str) -> Vec<Value> {
events
.iter()
.filter(|event| event["kind"] == kind)
.map(|event| event["payload"].clone())
.collect()
}
fn shift_of(check: &Value) -> [f64; 2] {
let matrix = &check["correction"]["matrix"];
[
matrix[0][2].as_f64().expect("a shift"),
matrix[1][2].as_f64().expect("a shift"),
]
}
async fn serving(journey: &Journey, frames: Vec<Vec<u8>>, interval_s: i64) -> (Running, Camera) {
serving_under(journey, calibration(), frames, interval_s).await
}
async fn serving_under(
journey: &Journey,
calibration: Value,
frames: Vec<Vec<u8>>,
interval_s: i64,
) -> (Running, Camera) {
let host = ScriptedHost::answering(frames.into_iter().map(Scripted::frame).collect()).await;
let camera = Camera {
host,
calibration: Some(calibration),
snapshot: true,
};
let started = journey.start(&camera, interval_s, &json!([])).await;
(started.server, camera)
}
async fn checked_and_started(
journey: &Journey,
sheet: &str,
empty: Vec<Vec<u8>>,
starting: impl Fn(&[Value]) -> Value,
position: u64,
) -> (Vec<Value>, PrintId) {
journey.octoprint.reports("Operational", JobScript::idle());
let count = empty.len();
let (server, _camera) = serving(journey, empty, 3600).await;
let mut checks = Vec::new();
for _ in 0..count {
checks.push(checked(&server, sheet, 30.0).await);
}
let print_id = started_under(&server, sheet, &starting(&checks)).await;
job_at(journey, position);
server.stop().await;
(checks, print_id)
}
struct Drawn<'a> {
spool: &'a printobserver_core::GcodeIndex,
local: &'a printobserver_core::GcodeIndex,
url: &'a str,
calibration: &'a printobserver_panels::CameraCalibration,
correction: Option<[f64; 2]>,
}
impl Drawn<'_> {
fn holds(
&self,
file: &str,
position: u64,
image: &[u8],
frame: &[u8],
earlier: Option<(&[u8], Timestamp)>,
) -> bool {
let of = |index| {
expected_check(
index,
position,
frame,
earlier,
self.url,
self.calibration,
self.correction,
)
};
let drawn = of(self.spool);
assert_eq!(
image, drawn.jpeg,
"{file} is drawn through the camera check's correction, split where the job \
stands in OctoPrint's copy"
);
let misplaced = of(self.local);
if misplaced.text == drawn.text {
return false;
}
assert_ne!(
image, misplaced.jpeg,
"{file}: the split is not where the slicer's local copy stands"
);
true
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_print_started_under_an_aligned_check_is_drawn_from_its_first_check() {
let slice = box_slice();
let journey = Journey::new(INSTALLER, &slice, 0);
let (made, print_id) = checked_and_started(
&journey,
"smooth-pei",
vec![frame("empty-sheets", "smooth-pei-z030.jpg")],
|made| made[0]["id"].clone(),
JUDGED[0].1,
)
.await;
let check = made[0].clone();
assert_eq!(check["verdict"], "aligned", "{check:#}");
let mut frames: Vec<Vec<u8>> = JUDGED.iter().map(|(file, _)| frame(CASE, file)).collect();
let moved = shifted(&frame(CASE, JUDGED[2].0), 40);
frames.push(moved.clone());
let mut checks = Checks::holding(&journey);
let (server, camera) = serving(&journey, frames.clone(), INTERVAL_S).await;
let url = camera.host.url();
let spool = tempfile::TempDir::new().expect("a spool directory");
let index = index_of(&slice, &spool.path().join("index.gcode"));
let local = index_of(&local_box_slice(), &spool.path().join("local.gcode"));
let calibrated = calibration_at(&calibration(), &url);
let mut previous: Option<(Vec<u8>, Timestamp)> = None;
let mut told_apart = 0;
for (at, (file, position)) in JUDGED.iter().enumerate() {
let seen = checks.next(*position).await;
let shown = situation(&seen);
assert_eq!(shown["image_kind"], "three_panel", "{file}: {shown:#}");
let (_, image) = handed(&seen);
let earlier = previous.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at));
let drawn = Drawn {
spool: &index,
local: &local,
url: &url,
calibration: &calibrated,
correction: Some(shift_of(&check)),
};
told_apart += usize::from(drawn.holds(file, *position, &image, &frames[at], earlier));
previous = Some((frames[at].clone(), captured_at(&seen)));
}
assert!(
told_apart > 0,
"at least one check stands somewhere else in the slicer's local copy"
);
let events = history(&server, print_id).await;
let judged: Vec<String> = payloads(&events, "first_layer_alignment_judged")
.iter()
.map(|payload| {
payload["frame_sha256"]
.as_str()
.unwrap_or_default()
.to_owned()
})
.collect();
for (file, _) in &JUDGED[..2] {
assert!(
judged.contains(&sha256(&frame(CASE, file))),
"{file}'s first-layer judgement is still recorded: {judged:#?}"
);
}
let started = payloads(&events, "print_started");
assert_eq!(started[0]["camera_check"], check["id"], "{started:#?}");
let seen = checks.next(LATER).await;
let shown = situation(&seen);
assert_eq!(shown["image_kind"], "whole_frame", "{shown:#}");
assert_eq!(
shown["image_fallback"]["code"], "view_refit_rejected",
"{shown:#}"
);
let events = history(&server, print_id).await;
let changed = payloads(&events, "check_image_changed");
assert!(
changed
.iter()
.any(|payload| payload["kind"] == "whole_frame"
&& payload["fallback"]["code"] == "view_refit_rejected"
&& payload["frame_sha256"] == sha256(&moved)),
"the change to the plain frame is noticed, naming why: {changed:#?}"
);
assert!(
!journey
.octoprint
.job_commands()
.iter()
.any(|command| command == "pause"),
"a moved camera pauses nothing"
);
checks.release();
server.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_shifted_camera_is_drawn_through_the_shift_its_check_found() {
let slice = box_slice();
let journey = Journey::new(INSTALLER, &slice, 0);
let empty = frame("empty-sheets", "textured-pei-z030.jpg");
let (made, _print_id) = checked_and_started(
&journey,
"textured-pei",
vec![empty.clone(), shifted(&empty, 4)],
|made| made[1]["id"].clone(),
JUDGED[0].1,
)
.await;
let (original, copy) = (&made[0], &made[1]);
for answer in [&original, ©] {
assert_eq!(answer["verdict"], "aligned", "{answer:#}");
}
let [ox, oy] = shift_of(original);
let [cx, cy] = shift_of(copy);
assert!(
(cx - ox - 4.0).hypot(cy - oy) <= 1.0,
"the copy's correction is the original's moved 4 px right: {:?} against {:?}",
[cx, cy],
[ox, oy]
);
let offset = copy["offset_px"].as_f64().expect("an offset");
assert!(
(offset - cx.hypot(cy)).abs() <= 1.0,
"the copy's offset is the length of its translation: {offset} against {:?}",
[cx, cy]
);
assert!(
cx.hypot(cy) > 1.0,
"the copy's correction moves the drawing"
);
let print_frame = shifted(&frame(CASE, JUDGED[0].0), 4);
let mut checks = Checks::holding(&journey);
let (server, camera) = serving(&journey, vec![print_frame.clone()], INTERVAL_S).await;
let url = camera.host.url();
let seen = checks.next(JUDGED[0].1).await;
assert_eq!(situation(&seen)["image_kind"], "three_panel");
let (_, image) = handed(&seen);
let spool = tempfile::TempDir::new().expect("a spool directory");
let index = index_of(&slice, &spool.path().join("index.gcode"));
let calibrated = calibration_at(&calibration(), &url);
let drawn = |correction: Option<[f64; 2]>| {
expected_composite(
&index,
JUDGED[0].1,
&print_frame,
None,
&url,
&calibrated,
correction,
)
};
assert_eq!(
image,
drawn(Some([cx, cy])),
"the first check is drawn through the copy's correction"
);
assert_ne!(
image,
drawn(None),
"the first check is not drawn where the uncorrected projection puts it"
);
checks.release();
server.stop().await;
}
const NOV_29: &str = "two-colour-box-2026-11-29";
const NOV_29_EMPTY: (&str, f64) = ("131508-empty-smooth-pei.jpg", 59.67);
const NOV_29_JUDGED: [&str; 10] = [
"131554-b01119f6990d.jpg",
"131755-5842c74b5065.jpg",
"131956-8a3ce32a6fef.jpg",
"132157-5d22bfb320b6.jpg",
"132358-816895e6f37e.jpg",
"132902-97a82c15735e.jpg",
"133103-1641ff612f0d.jpg",
"133433-6a83aa24e6f8.jpg",
"133634-c89df3006848.jpg",
"134237-d01779ded38c.jpg",
];
async fn nov_29_print(
journey: &Journey,
frames: Vec<Vec<u8>>,
) -> (Value, PrintId, Running, Camera) {
let calibration = calibration_named("core-one-2026-11-29.json");
journey.octoprint.reports("Operational", JobScript::idle());
let (server, _camera) = serving_under(
journey,
calibration.clone(),
vec![frame(NOV_29, NOV_29_EMPTY.0)],
3600,
)
.await;
let check = checked(&server, "smooth-pei", NOV_29_EMPTY.1).await;
assert_eq!(check["verdict"], "aligned", "{check:#}");
let print_id = started_under(&server, "smooth-pei", &check["id"]).await;
job_at(journey, JUDGED[0].1);
server.stop().await;
let (server, camera) = serving_under(journey, calibration, frames, INTERVAL_S).await;
(check, print_id, server, camera)
}
fn measured(camera: &Camera, bytes: &[u8]) -> Vec<printobserver_panels::FoundLandmark> {
let url = camera.host.url();
let calibrated = calibration_at(&calibration_named("core-one-2026-11-29.json"), &url);
printobserver_panels::landmarks_in_frame(&calibrated, bytes, &url)
.expect("the frame is the calibration's")
}
fn carries_its_frames_landmarks(
judged: &Value,
found: &[printobserver_panels::FoundLandmark],
what: &str,
) {
let carried = judged["landmarks"].as_array().unwrap_or_else(|| {
panic!("{what}: the judgement says which landmarks it measured: {judged:#}")
});
assert_eq!(carried.len(), found.len(), "{what}: {judged:#}");
for (carried, found) in carried.iter().zip(found) {
assert_eq!(carried["name"], found.name.as_str(), "{what}");
for axis in 0..2 {
let written = carried["offset_px"][axis].as_f64().expect("an offset");
assert!(
(written - found.located.offset_px[axis]).abs() < 1e-9,
"{what}: {} is written at {written} on axis {axis}, and the frame shows it at {}",
found.name,
found.located.offset_px[axis]
);
}
let score = carried["score"].as_f64().expect("a score");
assert!(
(score - f64::from(found.located.score)).abs() < 1e-6,
"{what}: {}",
found.name
);
assert_eq!(
carried["visible"],
found.visible(),
"{what}: {}",
found.name
);
}
}
fn residual_from(reference: &Value, found: &[printobserver_panels::FoundLandmark]) -> f64 {
let distances: Vec<f64> = found
.iter()
.filter(|landmark| landmark.visible())
.filter_map(|landmark| {
let at = reference["landmarks"]
.as_array()?
.iter()
.find(|kept| kept["name"] == landmark.name.as_str())?;
let [x, y] = [0, 1].map(|axis| at["offset_px"][axis].as_f64().unwrap_or(f64::NAN));
Some((landmark.located.offset_px[0] - x).hypot(landmark.located.offset_px[1] - y))
})
.collect();
let count = f64::from(u32::try_from(distances.len()).expect("a few"));
(distances
.iter()
.map(|distance| distance * distance)
.sum::<f64>()
/ count)
.sqrt()
}
#[tokio::test(flavor = "multi_thread")]
async fn each_check_of_an_unmoved_camera_records_its_own_frames_landmarks() {
let slice = box_slice();
let journey = Journey::new(INSTALLER, &slice, 0);
let frames: Vec<Vec<u8>> = NOV_29_JUDGED
.iter()
.map(|file| frame(NOV_29, file))
.collect();
let (check, print_id, server, camera) = nov_29_print(&journey, frames.clone()).await;
let sent = journey.octoprint.job_commands();
let mut checks = Checks::holding(&journey);
for (at, file) in NOV_29_JUDGED.iter().enumerate() {
let position = JUDGED[0].1 + 7_000 * u64::try_from(at).expect("a few");
let seen = checks.next(position).await;
let shown = situation(&seen);
assert_eq!(shown["image_kind"], "three_panel", "{file}: {shown:#}");
assert!(shown["image_fallback"].is_null(), "{file}: {shown:#}");
}
let events = history(&server, print_id).await;
let judged = payloads(&events, "camera_view_judged");
assert_eq!(
judged.len(),
frames.len(),
"one judgement a check: {judged:#?}"
);
let tolerance = calibration_named("core-one-2026-11-29.json")["drift_tolerance_px"]
.as_f64()
.expect("a tolerance");
let mut residuals = Vec::new();
for ((file, bytes), judged) in NOV_29_JUDGED.iter().zip(&frames).zip(&judged) {
assert_eq!(judged["frame_sha256"], sha256(bytes), "{file}");
assert_eq!(
judged["schema_version"],
printobserver_server::CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
"{file} is written at the version carrying its own measurements"
);
assert_eq!(judged["outcome"], "unshifted", "{file}: {judged:#}");
assert_eq!(
judged["view_correction"], check["correction"],
"{file} is judged against the camera check's correction"
);
let found = measured(&camera, bytes);
carries_its_frames_landmarks(judged, &found, file);
let residual = judged["residual_px"].as_f64().expect("a residual");
let expected = residual_from(&check["correction"], &found);
assert!(
(residual - expected).abs() < 1e-9,
"{file}: its residual is its own landmarks' from the check's: {residual} against {expected}"
);
assert!(residual < tolerance, "{file}: {residual} px");
residuals.push(residual);
}
let first = residuals[0];
assert!(
residuals
.iter()
.any(|residual| (residual - first).abs() > 1e-6),
"the frames' own residuals are not one number repeated: {residuals:?}"
);
let offsets: Vec<&Value> = judged.iter().map(|payload| &payload["landmarks"]).collect();
assert!(
offsets.iter().any(|landmarks| *landmarks != offsets[0]),
"the frames' own landmark offsets are not one set repeated"
);
assert!(
payloads(&events, "camera_view_refit").is_empty(),
"no re-fit"
);
assert!(
payloads(&events, "camera_degraded").is_empty(),
"no camera notice"
);
let changed = payloads(&events, "check_image_changed");
assert!(
changed
.iter()
.all(|payload| payload["kind"] == "three_panel" && payload["fallback"].is_null()),
"no check is shown the plain frame: {changed:#?}"
);
assert_eq!(
journey.octoprint.job_commands(),
sent,
"an unmoved camera sends the printer nothing after the print's start"
);
checks.release();
server.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_camera_knocked_between_two_checks_is_measured_and_refused_on_the_second() {
let slice = box_slice();
let journey = Journey::new(INSTALLER, &slice, 0);
let before = frame(NOV_29, NOV_29_JUDGED[3]);
let after = shifted(&before, 40);
let frames = vec![before.clone(), after.clone()];
let (check, print_id, server, camera) = nov_29_print(&journey, frames).await;
let sent = journey.octoprint.job_commands();
let mut checks = Checks::holding(&journey);
let seen = checks.next(JUDGED[0].1).await;
assert_eq!(situation(&seen)["image_kind"], "three_panel");
let seen = checks.next(JUDGED[1].1).await;
let shown = situation(&seen);
assert_eq!(shown["image_kind"], "whole_frame", "{shown:#}");
assert_eq!(
shown["image_fallback"]["code"], "view_refit_rejected",
"{shown:#}"
);
let events = history(&server, print_id).await;
let judged = payloads(&events, "camera_view_judged");
assert_eq!(judged.len(), 2, "{judged:#?}");
assert_eq!(judged[0]["frame_sha256"], sha256(&before));
assert_eq!(judged[1]["frame_sha256"], sha256(&after));
for payload in &judged {
assert_eq!(
payload["schema_version"],
printobserver_server::CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
"{payload:#}"
);
}
assert_eq!(judged[0]["outcome"], "unshifted", "{:#}", judged[0]);
assert_eq!(
judged[1]["outcome"], "view_refit_rejected",
"{:#}",
judged[1]
);
let (found_before, found_after) = (measured(&camera, &before), measured(&camera, &after));
carries_its_frames_landmarks(&judged[0], &found_before, "before the knock");
carries_its_frames_landmarks(&judged[1], &found_after, "after the knock");
let moved = found_before
.iter()
.zip(&found_after)
.filter(|(was, now)| was.visible() && now.visible())
.filter(|(was, now)| {
(now.located.offset_px[0] - was.located.offset_px[0] - 40.0).abs() <= 2.0
&& (now.located.offset_px[1] - was.located.offset_px[1]).abs() <= 2.0
})
.count();
assert!(
moved >= 2,
"the second frame's landmarks moved with the knock"
);
let residual = |payload: &Value| payload["residual_px"].as_f64().expect("a residual");
assert!(residual(&judged[0]) < 6.0, "{:#}", judged[0]);
assert!(
(residual(&judged[1]) - residual_from(&check["correction"], &found_after)).abs() < 1e-9
&& residual(&judged[1]) > 30.0,
"the second frame's residual is the knock's: {:#}",
judged[1]
);
assert_eq!(
journey.octoprint.job_commands(),
sent,
"a knocked camera sends the printer nothing after the print's start"
);
checks.release();
server.stop().await;
}