1use printobserver_panels::{ViewCorrection, ViewJudgement, ViewOutcome};
16use printobserver_supervisor_api::{ImageFallback, ImageKind};
17use printobserver_types::EventPayload;
18use printobserver_types::contract::Sample;
19use printobserver_types::schemars::JsonSchema;
20use printobserver_types::serde::{Deserialize, Deserializer, Serialize};
21
22pub const CAMERA_VIEW_JUDGED_SCHEMA_VERSION: u32 = 2;
30
31const fn camera_view_judged_first_version() -> u32 {
33 1
34}
35
36fn known_camera_view_judged_version<'de, D>(deserializer: D) -> Result<u32, D::Error>
40where
41 D: Deserializer<'de>,
42{
43 let version = u32::deserialize(deserializer)?;
44 if (1..=CAMERA_VIEW_JUDGED_SCHEMA_VERSION).contains(&version) {
45 Ok(version)
46 } else {
47 Err(printobserver_types::serde::de::Error::custom(format!(
48 "schema_version is {version}, and this program reads camera_view_judged versions 1 to {CAMERA_VIEW_JUDGED_SCHEMA_VERSION}"
49 )))
50 }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
55#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
56#[schemars(crate = "printobserver_types::schemars")]
57pub enum AlignmentJudgedVerdict {
58 Passed,
61 Inconclusive,
63 Failed,
66}
67
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
70#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
71#[schemars(crate = "printobserver_types::schemars")]
72pub struct FirstLayerAlignmentJudgedPayload {
73 pub verdict: AlignmentJudgedVerdict,
75 pub offset_px: Option<f64>,
78 pub correction_px: Option<[f64; 2]>,
81 pub match_strength: Option<f64>,
84 pub reason: String,
87 pub frame_sha256: String,
89 pub view_correction: Option<ViewCorrection>,
92}
93
94impl EventPayload for FirstLayerAlignmentJudgedPayload {
95 const KIND: &'static str = "first_layer_alignment_judged";
96}
97
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
105#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
106#[schemars(crate = "printobserver_types::schemars")]
107pub struct CameraViewJudgedPayload {
108 #[serde(
112 default = "camera_view_judged_first_version",
113 deserialize_with = "known_camera_view_judged_version"
114 )]
115 #[schemars(range(min = 1, max = CAMERA_VIEW_JUDGED_SCHEMA_VERSION))]
116 pub schema_version: u32,
117 pub frame_sha256: String,
119 pub outcome: ViewOutcome,
121 pub view_correction: Option<ViewCorrection>,
125 pub reason: Option<String>,
129 #[serde(default, skip_serializing_if = "Vec::is_empty")]
133 pub landmarks: Vec<JudgedLandmark>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub residual_px: Option<f64>,
141}
142
143#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
145#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
146#[schemars(crate = "printobserver_types::schemars")]
147pub struct JudgedLandmark {
148 pub name: String,
150 pub offset_px: [f64; 2],
153 pub score: f64,
155 pub visible: bool,
159 #[serde(default, skip_serializing_if = "Option::is_none")]
163 pub from_reference_px: Option<f64>,
164}
165
166impl CameraViewJudgedPayload {
167 #[must_use]
171 pub fn of(
172 frame_sha256: &str,
173 view: &ViewJudgement,
174 view_correction: Option<ViewCorrection>,
175 reason: Option<String>,
176 ) -> Self {
177 let landmarks: Vec<JudgedLandmark> = view
178 .landmarks
179 .iter()
180 .map(|found| JudgedLandmark {
181 name: found.name.clone(),
182 offset_px: found.located.offset_px,
183 score: f64::from(found.located.score),
184 visible: found.visible(),
185 from_reference_px: view_correction.as_ref().and_then(|correction| {
186 correction
187 .landmarks
188 .iter()
189 .find(|reference| reference.name == found.name)
190 .map(|reference| {
191 (found.located.offset_px[0] - reference.offset_px[0])
192 .hypot(found.located.offset_px[1] - reference.offset_px[1])
193 })
194 }),
195 })
196 .collect();
197 let compared: Vec<f64> = landmarks
198 .iter()
199 .filter(|landmark| landmark.visible)
200 .filter_map(|landmark| match view_correction {
201 Some(_) => landmark.from_reference_px,
202 None => Some(landmark.offset_px[0].hypot(landmark.offset_px[1])),
203 })
204 .collect();
205 let residual_px = (!compared.is_empty()).then(|| {
206 let count = f64::from(u32::try_from(compared.len()).unwrap_or(u32::MAX));
207 (compared
208 .iter()
209 .map(|distance| distance * distance)
210 .sum::<f64>()
211 / count)
212 .sqrt()
213 });
214 Self {
215 schema_version: CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
216 frame_sha256: frame_sha256.to_owned(),
217 outcome: view.outcome,
218 view_correction,
219 reason,
220 landmarks,
221 residual_px,
222 }
223 }
224}
225
226impl EventPayload for CameraViewJudgedPayload {
227 const KIND: &'static str = "camera_view_judged";
228}
229
230#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
234#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
235#[schemars(crate = "printobserver_types::schemars")]
236pub struct CameraViewRefitPayload {
237 pub frame_sha256: String,
239 pub view_correction: ViewCorrection,
241}
242
243impl EventPayload for CameraViewRefitPayload {
244 const KIND: &'static str = "camera_view_refit";
245}
246
247#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
251#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
252#[schemars(crate = "printobserver_types::schemars")]
253pub struct CheckImageChangedPayload {
254 pub kind: ImageKind,
256 pub fallback: Option<ImageFallback>,
258 pub frame_sha256: String,
260}
261
262impl EventPayload for CheckImageChangedPayload {
263 const KIND: &'static str = "check_image_changed";
264}
265
266const SAMPLE_SHA256: &str = "9f2c4d1e8b7a6f5e4d3c2b1a0f9e8d7c6b5a4f3e2d1c0b9a8f7e6d5c4b3a2f1e";
268
269fn sample_correction() -> ViewCorrection {
271 ViewCorrection::translation(
272 [14.0, 4.0],
273 vec![
274 printobserver_panels::ReferenceLandmark {
275 name: "frame-screws-right-front".to_owned(),
276 offset_px: [59.1, 0.7],
277 score: 0.83,
278 },
279 printobserver_panels::ReferenceLandmark {
280 name: "frame-label-right".to_owned(),
281 offset_px: [79.6, 0.2],
282 score: 0.84,
283 },
284 ],
285 )
286}
287
288impl Sample for FirstLayerAlignmentJudgedPayload {
289 fn sample_full() -> Self {
290 Self {
291 verdict: AlignmentJudgedVerdict::Passed,
292 offset_px: Some(14.6),
293 correction_px: Some([14.0, 4.0]),
294 match_strength: Some(57.6),
295 reason: "clearly_found".to_owned(),
296 frame_sha256: SAMPLE_SHA256.to_owned(),
297 view_correction: Some(sample_correction()),
298 }
299 }
300
301 fn sample_minimal() -> Self {
302 Self {
303 verdict: AlignmentJudgedVerdict::Inconclusive,
304 offset_px: None,
305 correction_px: None,
306 match_strength: None,
307 reason: "not_clearly_found".to_owned(),
308 frame_sha256: SAMPLE_SHA256.to_owned(),
309 view_correction: None,
310 }
311 }
312
313 fn sample_alternates() -> Vec<Self> {
314 vec![Self {
315 verdict: AlignmentJudgedVerdict::Failed,
316 reason: "the camera is not the stream the calibration was fitted on".to_owned(),
317 ..Self::sample_minimal()
318 }]
319 }
320}
321
322impl Sample for CameraViewJudgedPayload {
323 fn sample_full() -> Self {
324 Self {
325 schema_version: CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
326 frame_sha256: SAMPLE_SHA256.to_owned(),
327 outcome: ViewOutcome::ViewRefitRejected,
328 view_correction: Some(sample_correction()),
329 reason: Some(
330 "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"
331 .to_owned(),
332 ),
333 landmarks: vec![
334 JudgedLandmark {
335 name: "frame-screws-right-front".to_owned(),
336 offset_px: [68.4, 1.1],
337 score: 0.81,
338 visible: true,
339 from_reference_px: Some(9.3),
340 },
341 JudgedLandmark {
342 name: "frame-label-right".to_owned(),
343 offset_px: [89.8, 0.4],
344 score: 0.79,
345 visible: true,
346 from_reference_px: Some(10.2),
347 },
348 JudgedLandmark {
349 name: "chassis-corner-top-right".to_owned(),
350 offset_px: [12.0, -40.5],
351 score: 0.31,
352 visible: false,
353 from_reference_px: None,
354 },
355 ],
356 residual_px: Some(9.76),
357 }
358 }
359
360 fn sample_minimal() -> Self {
361 Self {
362 schema_version: CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
363 frame_sha256: SAMPLE_SHA256.to_owned(),
364 outcome: ViewOutcome::Unshifted,
365 view_correction: None,
366 reason: None,
367 landmarks: Vec::new(),
368 residual_px: None,
369 }
370 }
371
372 fn sample_alternates() -> Vec<Self> {
373 [
374 ViewOutcome::Refit,
375 ViewOutcome::LandmarksNotFound,
376 ViewOutcome::FrameMismatch,
377 ]
378 .into_iter()
379 .map(|outcome| Self {
380 outcome,
381 ..Self::sample_minimal()
382 })
383 .collect()
384 }
385}
386
387impl Sample for CameraViewRefitPayload {
388 fn sample_full() -> Self {
389 Self {
390 frame_sha256: SAMPLE_SHA256.to_owned(),
391 view_correction: sample_correction(),
392 }
393 }
394}
395
396impl Sample for CheckImageChangedPayload {
397 fn sample_full() -> Self {
398 Self {
399 kind: ImageKind::WholeFrame,
400 fallback: Some(ImageFallback::sample_full()),
401 frame_sha256: SAMPLE_SHA256.to_owned(),
402 }
403 }
404
405 fn sample_minimal() -> Self {
406 Self {
407 kind: ImageKind::ThreePanel,
408 fallback: None,
409 frame_sha256: SAMPLE_SHA256.to_owned(),
410 }
411 }
412}