printobserver-server 0.20.2

The printobserver server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! The records of what the server judged of a print's camera frames.
//!
//! Every judgement of a print's first-layer alignment and of its camera's view
//! is written into the print's history, each naming by its SHA-256 the stored
//! frame it was made on ([`printobserver_core::ImageRef::sha256`]), so a
//! reader can open the very frame behind any verdict. Two further kinds are
//! change notices rather than judgements: the correction a pass put in force
//! while the landmarks had moved ([`CameraViewRefitPayload`]), and each change
//! in which image a print's checks are shown, with its reason
//! ([`CheckImageChangedPayload`]).
//!
//! This crate alone writes these kinds, so it declares them, as it declares the
//! startup reconciliation.

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};

/// The version of the `camera_view_judged` record this server writes.
///
/// Version 1 carried the frame, its outcome, its reason and the correction in
/// force, and stated no version: a record with none is a version-1 record.
/// Version 2 added `landmarks` and `residual_px`, what the judgement measured
/// on its own frame, so a reader can tell a record that measured nothing it
/// could write from one written before there was anywhere to write it.
pub const CAMERA_VIEW_JUDGED_SCHEMA_VERSION: u32 = 2;

/// The version a `camera_view_judged` record stating none is at.
const fn camera_view_judged_first_version() -> u32 {
    1
}

/// A `camera_view_judged` record's version, refusing one this server does not
/// know: a later one is written by a later release, whose fields this reading
/// would silently lose.
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}"
        )))
    }
}

/// What one judgement of a print's first layer came to.
#[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 {
    /// The first layer is clearly found, and its offset is the print's
    /// correction from now on.
    Passed,
    /// The frame could not tell; a later check's frame is judged again.
    Inconclusive,
    /// The camera's frames cannot be judged against the calibration, which
    /// holds for the rest of the print.
    Failed,
}

/// One judgement of a print's first-layer alignment, on one frame.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct FirstLayerAlignmentJudgedPayload {
    /// What it came to.
    pub verdict: AlignmentJudgedVerdict,
    /// How far the printed first layer was found from its uncorrected
    /// projection, in calibration pixels; null when it was not searched for.
    pub offset_px: Option<f64>,
    /// The correction the pass put in force, `[dx, dy]` pixels; null unless it
    /// passed.
    pub correction_px: Option<[f64; 2]>,
    /// The peak smoothed contrast the layer was found at, in grey levels; null
    /// when it was not searched for.
    pub match_strength: Option<f64>,
    /// `clearly_found` for a pass, `covered` or `not_clearly_found` for an
    /// inconclusive judgement, and the failure's own sentence for a failure.
    pub reason: String,
    /// The stored frame it was judged on.
    pub frame_sha256: String,
    /// The correction in force when the frame was judged; null before the
    /// print's first pass.
    pub view_correction: Option<ViewCorrection>,
}

impl EventPayload for FirstLayerAlignmentJudgedPayload {
    const KIND: &'static str = "first_layer_alignment_judged";
}

/// One judgement of a print's camera view, on one frame: one for every
/// judgement, whatever it found and whether or not it repeats the last.
///
/// `view_correction` is what the frame was judged *against*, so it repeats
/// from check to check for as long as one correction stays in force;
/// `landmarks` and `residual_px` are what was measured on *this* frame.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CameraViewJudgedPayload {
    /// The version of this record: the schema's maximum for every record
    /// this server writes, and 1 for a record stating none, which was written
    /// before `landmarks` and `residual_px` existed.
    #[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,
    /// The stored frame it was judged on.
    pub frame_sha256: String,
    /// What it found.
    pub outcome: ViewOutcome,
    /// The correction in force when the frame was judged; null when none was.
    /// Its landmarks are the reference this frame was compared against, found
    /// on the frame the correction was taken on rather than on this one.
    pub view_correction: Option<ViewCorrection>,
    /// Why the frame may not be drawn on: for the three refusals, and for a
    /// refit view, whose camera has moved since its calibration; null for an
    /// unshifted one.
    pub reason: Option<String>,
    /// Every landmark of the calibration as this frame showed it, in the
    /// calibration's order; absent when the frame could not be searched, as
    /// one of another size or stream cannot.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub landmarks: Vec<JudgedLandmark>,
    /// The RMS distance, over this frame's visible landmarks, between where
    /// it showed them and where the judgement expected them: the correction
    /// in force's reference, over the landmarks it names, or each landmark's
    /// calibrated place when none is in force. Absent when no landmark it
    /// compared was visible.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub residual_px: Option<f64>,
}

/// One landmark of the calibration as one judged frame showed it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct JudgedLandmark {
    /// The calibration's name for it.
    pub name: String,
    /// How far from its calibrated place this frame showed it, `[dx, dy]`
    /// pixels.
    pub offset_px: [f64; 2],
    /// The correlation it was found at.
    pub score: f64,
    /// Whether it was found at all, rather than hidden by the head, the
    /// gantry or a part; a hidden landmark's offset is where its search
    /// scored best, and counts for nothing.
    pub visible: bool,
    /// How far it lies from where the correction in force's reference had it,
    /// in pixels; absent when no correction is in force or its reference does
    /// not name this landmark.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from_reference_px: Option<f64>,
}

impl CameraViewJudgedPayload {
    /// The record of one view judgement of the frame `frame_sha256`: what it
    /// found, and every landmark the judgement measured on that frame,
    /// against the correction in force.
    #[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";
}

/// A first-layer pass put a correction in force while the landmarks had moved
/// from the calibration: the print's first, or one taken again after the
/// camera moved again.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CameraViewRefitPayload {
    /// The stored frame the correction was taken on.
    pub frame_sha256: String,
    /// The correction now in force.
    pub view_correction: ViewCorrection,
}

impl EventPayload for CameraViewRefitPayload {
    const KIND: &'static str = "camera_view_refit";
}

/// The image a print's checks are shown changed: its first check's image, and
/// every check whose image kind or fallback code differs from the last one
/// recorded.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CheckImageChangedPayload {
    /// Which image the check was shown.
    pub kind: ImageKind,
    /// Why it was the whole frame; null for the three-panel image.
    pub fallback: Option<ImageFallback>,
    /// The stored frame the check's image was made of.
    pub frame_sha256: String,
}

impl EventPayload for CheckImageChangedPayload {
    const KIND: &'static str = "check_image_changed";
}

/// A frame's SHA-256, as samples name one.
const SAMPLE_SHA256: &str = "9f2c4d1e8b7a6f5e4d3c2b1a0f9e8d7c6b5a4f3e2d1c0b9a8f7e6d5c4b3a2f1e";

/// The correction samples carry.
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(),
        }
    }
}