use printobserver_panels::{ViewCorrection, ViewJudgement, ViewOutcome};
use printobserver_supervisor_api::{ImageFallback, ImageKind};
use printobserver_types::EventPayload;
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Deserializer, Serialize};
pub const CAMERA_VIEW_JUDGED_SCHEMA_VERSION: u32 = 2;
const fn camera_view_judged_first_version() -> u32 {
1
}
fn known_camera_view_judged_version<'de, D>(deserializer: D) -> Result<u32, D::Error>
where
D: Deserializer<'de>,
{
let version = u32::deserialize(deserializer)?;
if (1..=CAMERA_VIEW_JUDGED_SCHEMA_VERSION).contains(&version) {
Ok(version)
} else {
Err(printobserver_types::serde::de::Error::custom(format!(
"schema_version is {version}, and this program reads camera_view_judged versions 1 to {CAMERA_VIEW_JUDGED_SCHEMA_VERSION}"
)))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum AlignmentJudgedVerdict {
Passed,
Inconclusive,
Failed,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct FirstLayerAlignmentJudgedPayload {
pub verdict: AlignmentJudgedVerdict,
pub offset_px: Option<f64>,
pub correction_px: Option<[f64; 2]>,
pub match_strength: Option<f64>,
pub reason: String,
pub frame_sha256: String,
pub view_correction: Option<ViewCorrection>,
}
impl EventPayload for FirstLayerAlignmentJudgedPayload {
const KIND: &'static str = "first_layer_alignment_judged";
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CameraViewJudgedPayload {
#[serde(
default = "camera_view_judged_first_version",
deserialize_with = "known_camera_view_judged_version"
)]
#[schemars(range(min = 1, max = CAMERA_VIEW_JUDGED_SCHEMA_VERSION))]
pub schema_version: u32,
pub frame_sha256: String,
pub outcome: ViewOutcome,
pub view_correction: Option<ViewCorrection>,
pub reason: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub landmarks: Vec<JudgedLandmark>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub residual_px: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct JudgedLandmark {
pub name: String,
pub offset_px: [f64; 2],
pub score: f64,
pub visible: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from_reference_px: Option<f64>,
}
impl CameraViewJudgedPayload {
#[must_use]
pub fn of(
frame_sha256: &str,
view: &ViewJudgement,
view_correction: Option<ViewCorrection>,
reason: Option<String>,
) -> Self {
let landmarks: Vec<JudgedLandmark> = view
.landmarks
.iter()
.map(|found| JudgedLandmark {
name: found.name.clone(),
offset_px: found.located.offset_px,
score: f64::from(found.located.score),
visible: found.visible(),
from_reference_px: view_correction.as_ref().and_then(|correction| {
correction
.landmarks
.iter()
.find(|reference| reference.name == found.name)
.map(|reference| {
(found.located.offset_px[0] - reference.offset_px[0])
.hypot(found.located.offset_px[1] - reference.offset_px[1])
})
}),
})
.collect();
let compared: Vec<f64> = landmarks
.iter()
.filter(|landmark| landmark.visible)
.filter_map(|landmark| match view_correction {
Some(_) => landmark.from_reference_px,
None => Some(landmark.offset_px[0].hypot(landmark.offset_px[1])),
})
.collect();
let residual_px = (!compared.is_empty()).then(|| {
let count = f64::from(u32::try_from(compared.len()).unwrap_or(u32::MAX));
(compared
.iter()
.map(|distance| distance * distance)
.sum::<f64>()
/ count)
.sqrt()
});
Self {
schema_version: CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
frame_sha256: frame_sha256.to_owned(),
outcome: view.outcome,
view_correction,
reason,
landmarks,
residual_px,
}
}
}
impl EventPayload for CameraViewJudgedPayload {
const KIND: &'static str = "camera_view_judged";
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CameraViewRefitPayload {
pub frame_sha256: String,
pub view_correction: ViewCorrection,
}
impl EventPayload for CameraViewRefitPayload {
const KIND: &'static str = "camera_view_refit";
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CheckImageChangedPayload {
pub kind: ImageKind,
pub fallback: Option<ImageFallback>,
pub frame_sha256: String,
}
impl EventPayload for CheckImageChangedPayload {
const KIND: &'static str = "check_image_changed";
}
const SAMPLE_SHA256: &str = "9f2c4d1e8b7a6f5e4d3c2b1a0f9e8d7c6b5a4f3e2d1c0b9a8f7e6d5c4b3a2f1e";
fn sample_correction() -> ViewCorrection {
ViewCorrection::translation(
[14.0, 4.0],
vec![
printobserver_panels::ReferenceLandmark {
name: "frame-screws-right-front".to_owned(),
offset_px: [59.1, 0.7],
score: 0.83,
},
printobserver_panels::ReferenceLandmark {
name: "frame-label-right".to_owned(),
offset_px: [79.6, 0.2],
score: 0.84,
},
],
)
}
impl Sample for FirstLayerAlignmentJudgedPayload {
fn sample_full() -> Self {
Self {
verdict: AlignmentJudgedVerdict::Passed,
offset_px: Some(14.6),
correction_px: Some([14.0, 4.0]),
match_strength: Some(57.6),
reason: "clearly_found".to_owned(),
frame_sha256: SAMPLE_SHA256.to_owned(),
view_correction: Some(sample_correction()),
}
}
fn sample_minimal() -> Self {
Self {
verdict: AlignmentJudgedVerdict::Inconclusive,
offset_px: None,
correction_px: None,
match_strength: None,
reason: "not_clearly_found".to_owned(),
frame_sha256: SAMPLE_SHA256.to_owned(),
view_correction: None,
}
}
fn sample_alternates() -> Vec<Self> {
vec![Self {
verdict: AlignmentJudgedVerdict::Failed,
reason: "the camera is not the stream the calibration was fitted on".to_owned(),
..Self::sample_minimal()
}]
}
}
impl Sample for CameraViewJudgedPayload {
fn sample_full() -> Self {
Self {
schema_version: CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
frame_sha256: SAMPLE_SHA256.to_owned(),
outcome: ViewOutcome::ViewRefitRejected,
view_correction: Some(sample_correction()),
reason: Some(
"the camera has moved again since this print's first-layer correction was taken: frame-label-right is 10.2 px from where that correction's frame had it"
.to_owned(),
),
landmarks: vec![
JudgedLandmark {
name: "frame-screws-right-front".to_owned(),
offset_px: [68.4, 1.1],
score: 0.81,
visible: true,
from_reference_px: Some(9.3),
},
JudgedLandmark {
name: "frame-label-right".to_owned(),
offset_px: [89.8, 0.4],
score: 0.79,
visible: true,
from_reference_px: Some(10.2),
},
JudgedLandmark {
name: "chassis-corner-top-right".to_owned(),
offset_px: [12.0, -40.5],
score: 0.31,
visible: false,
from_reference_px: None,
},
],
residual_px: Some(9.76),
}
}
fn sample_minimal() -> Self {
Self {
schema_version: CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
frame_sha256: SAMPLE_SHA256.to_owned(),
outcome: ViewOutcome::Unshifted,
view_correction: None,
reason: None,
landmarks: Vec::new(),
residual_px: None,
}
}
fn sample_alternates() -> Vec<Self> {
[
ViewOutcome::Refit,
ViewOutcome::LandmarksNotFound,
ViewOutcome::FrameMismatch,
]
.into_iter()
.map(|outcome| Self {
outcome,
..Self::sample_minimal()
})
.collect()
}
}
impl Sample for CameraViewRefitPayload {
fn sample_full() -> Self {
Self {
frame_sha256: SAMPLE_SHA256.to_owned(),
view_correction: sample_correction(),
}
}
}
impl Sample for CheckImageChangedPayload {
fn sample_full() -> Self {
Self {
kind: ImageKind::WholeFrame,
fallback: Some(ImageFallback::sample_full()),
frame_sha256: SAMPLE_SHA256.to_owned(),
}
}
fn sample_minimal() -> Self {
Self {
kind: ImageKind::ThreePanel,
fallback: None,
frame_sha256: SAMPLE_SHA256.to_owned(),
}
}
}