Skip to main content

printobserver_core/records/
preflight.rs

1//! Whether the spools loaded hold enough for a print, were sliced for, and
2//! suit the sheet it goes down on, asked before it starts.
3
4use printobserver_types::schemars::JsonSchema;
5use printobserver_types::serde::{Deserialize, Serialize};
6use printobserver_types::{FileName, Timestamp};
7
8use super::ids::SpoolId;
9use super::spool::{UnverifiedMark, UnverifiedMarks};
10
11/// What a filament check found, for one tool or for a whole print.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
13#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
14#[schemars(crate = "printobserver_types::schemars")]
15pub enum PreflightVerdict {
16    /// The spool holds what the print needs and its buffer.
17    Passed,
18    /// No tracked spool is loaded on the tool, so nothing was checked.
19    Unchecked,
20    /// The spool holds less than the print needs and its buffer.
21    Insufficient,
22    /// The spool's figure is in doubt.
23    UnverifiedSpool,
24    /// `OctoPrint`'s analysis of the file had still not appeared when the
25    /// start's wait for it elapsed, or has not appeared yet when the check is
26    /// only read.
27    NoAnalysis,
28    /// The start went ahead despite the check, because the actor said so.
29    Overridden,
30    /// The check is set to warn, and let an insufficient, unverified or
31    /// unanalysed start go ahead.
32    Warned,
33}
34
35/// What a filament check found for one tool.
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
37#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
38#[schemars(crate = "printobserver_types::schemars")]
39pub struct PreflightTool {
40    /// The tool, in the printer's own numbering.
41    pub tool: i64,
42    /// What the check found for it, with the evidence that finding rests on.
43    pub result: PreflightToolResult,
44}
45
46/// The spool a check judged, named beside its identifier so a reader need
47/// not look it up.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
49#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
50#[schemars(crate = "printobserver_types::schemars")]
51pub struct PreflightSpool {
52    /// The spool's identifier.
53    pub id: SpoolId,
54    /// The spool's name.
55    pub name: String,
56}
57
58/// What a print needs from one spool, in grams: both figures a comparison
59/// with what the spool holds uses, or neither.
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
61#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
62#[schemars(crate = "printobserver_types::schemars")]
63pub struct PreflightNeed {
64    /// What the print needs from the spool, by the file's analysis and the
65    /// spool's own diameter and density.
66    pub required_g: f64,
67    /// The margin asked for beyond that.
68    pub buffer_g: f64,
69}
70
71/// A spool that holds less than the print needs and its buffer.
72#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
73#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
74#[schemars(crate = "printobserver_types::schemars")]
75pub struct ShortSpool {
76    /// The spool.
77    pub spool: PreflightSpool,
78    /// What the spool holds, in grams.
79    pub remaining_g: f64,
80    /// What the print needs from it.
81    pub need: PreflightNeed,
82    /// The spool's marks at the check, oldest first, so a spool both short
83    /// and unverified says both.
84    #[serde(default, skip_serializing_if = "Vec::is_empty")]
85    pub marks: Vec<UnverifiedMark>,
86}
87
88/// A spool whose figure is in doubt.
89#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
90#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
91#[schemars(crate = "printobserver_types::schemars")]
92pub struct DoubtedSpool {
93    /// The spool.
94    pub spool: PreflightSpool,
95    /// What the spool holds, in grams.
96    pub remaining_g: f64,
97    /// What the print needs from it, when the file's analysis says.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub need: Option<PreflightNeed>,
100    /// Every reason the spool's figure is in doubt, oldest first; never empty.
101    pub marks: UnverifiedMarks,
102}
103
104/// A spool on a tool of a file with no analysis, so what it needs is unknown.
105#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
106#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
107#[schemars(crate = "printobserver_types::schemars")]
108pub struct UnanalysedSpool {
109    /// The spool.
110    pub spool: PreflightSpool,
111    /// What the spool holds, in grams.
112    pub remaining_g: f64,
113}
114
115/// What a check that refuses a start found for one tool.
116#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
117#[serde(
118    crate = "printobserver_types::serde",
119    tag = "verdict",
120    rename_all = "snake_case",
121    deny_unknown_fields
122)]
123#[schemars(crate = "printobserver_types::schemars")]
124pub enum PreflightObjection {
125    /// The spool holds less than the print needs and its buffer.
126    Insufficient(ShortSpool),
127    /// The spool's figure is in doubt.
128    UnverifiedSpool(DoubtedSpool),
129    /// The file has no analysis, so what the spool must hold is unknown.
130    NoAnalysis(UnanalysedSpool),
131}
132
133impl PreflightObjection {
134    /// The verdict this objection is.
135    #[must_use]
136    pub const fn verdict(&self) -> PreflightVerdict {
137        match self {
138            Self::Insufficient(_) => PreflightVerdict::Insufficient,
139            Self::UnverifiedSpool(_) => PreflightVerdict::UnverifiedSpool,
140            Self::NoAnalysis(_) => PreflightVerdict::NoAnalysis,
141        }
142    }
143}
144
145/// What a filament check found for one tool, tagged by its verdict, each
146/// verdict carrying exactly the evidence it rests on.
147#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
148#[serde(
149    crate = "printobserver_types::serde",
150    tag = "verdict",
151    rename_all = "snake_case",
152    deny_unknown_fields
153)]
154#[schemars(crate = "printobserver_types::schemars")]
155pub enum PreflightToolResult {
156    /// The spool holds what the print needs and its buffer, and its figure is
157    /// not in doubt.
158    Passed {
159        /// The spool.
160        spool: PreflightSpool,
161        /// What the spool holds, in grams.
162        remaining_g: f64,
163        /// What the print needs from it.
164        need: PreflightNeed,
165    },
166    /// No tracked spool is loaded on the tool, so nothing was checked.
167    Unchecked,
168    /// The spool holds less than the print needs and its buffer.
169    Insufficient(ShortSpool),
170    /// The spool's figure is in doubt.
171    UnverifiedSpool(DoubtedSpool),
172    /// `OctoPrint`'s analysis of the file had not appeared, so what the spool
173    /// must hold is unknown.
174    NoAnalysis(UnanalysedSpool),
175    /// The start went ahead despite this objection, because an operator said
176    /// so.
177    Overridden {
178        /// What the check objected to.
179        objection: PreflightObjection,
180    },
181    /// The check is set to warn, and let the start go ahead despite this
182    /// objection.
183    Warned {
184        /// What the check objected to.
185        objection: PreflightObjection,
186    },
187}
188
189impl PreflightToolResult {
190    /// The verdict this result is.
191    #[must_use]
192    pub const fn verdict(&self) -> PreflightVerdict {
193        match self {
194            Self::Passed { .. } => PreflightVerdict::Passed,
195            Self::Unchecked => PreflightVerdict::Unchecked,
196            Self::Insufficient(_) => PreflightVerdict::Insufficient,
197            Self::UnverifiedSpool(_) => PreflightVerdict::UnverifiedSpool,
198            Self::NoAnalysis(_) => PreflightVerdict::NoAnalysis,
199            Self::Overridden { .. } => PreflightVerdict::Overridden,
200            Self::Warned { .. } => PreflightVerdict::Warned,
201        }
202    }
203}
204
205/// What a filament check found for one print.
206#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
207#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
208#[schemars(crate = "printobserver_types::schemars")]
209pub struct Preflight {
210    /// The file the print is of.
211    pub file_name: String,
212    /// What it found for each tool.
213    pub tools: Vec<PreflightTool>,
214    /// The worst of the tools' verdicts, in the order insufficient,
215    /// unverified spool, no analysis, warned, overridden, unchecked, passed.
216    ///
217    /// The filament weight's alone: the material and sheet checks carry
218    /// verdicts of their own, in `material` and `sheet`.
219    pub verdict: PreflightVerdict,
220    /// Whether the file was sliced for the material of the spool on tool 0.
221    /// Absent from a check recorded before this check existed.
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub material: Option<MaterialResult>,
224    /// Whether the declared build sheet suits that spool's material. Absent
225    /// from a check recorded before this check existed, and from a read that
226    /// was given no sheet.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub sheet: Option<SheetResult>,
229    /// Each stretch of a file with planned colour changes, the filament it
230    /// feeds and the spool meant for it: tool 0's result is checked against
231    /// segment 0 alone, and each later segment against the spool a start's
232    /// manifest names for it. Absent for a file that plans no change.
233    #[serde(default, skip_serializing_if = "Vec::is_empty")]
234    pub segments: Vec<PreflightSegment>,
235    /// When the check was made.
236    pub checked_at: Timestamp,
237}
238
239/// One stretch of a file with planned colour changes, as a filament check
240/// reads it.
241#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
242#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
243#[schemars(
244    crate = "printobserver_types::schemars",
245    transform = crate::gcode_index::null_is_sent
246)]
247pub struct PreflightSegment {
248    /// Its number: segment 0 runs from the file's start to the first change.
249    pub segment: u32,
250    /// Its colour as `#RRGGBB`; null when the file names none.
251    pub color: Option<String>,
252    /// The filament it feeds, in millimetres.
253    pub filament_mm: f64,
254    /// What it needs from the spool meant for it, in grams, by that spool's
255    /// diameter and density; null when no spool is there to convert with.
256    pub required_g: Option<f64>,
257    /// The spool meant for it: the one on tool 0 for segment 0, and the one
258    /// the manifest names for a later segment; null when none is.
259    pub spool_id: Option<SpoolId>,
260}
261
262/// A name that is never blank, trimmed of surrounding space as it is read.
263fn named_text(text: &str, what: &str) -> Result<String, String> {
264    let trimmed = text.trim();
265    if trimmed.is_empty() {
266        return Err(format!("{what} is named by something other than space"));
267    }
268    Ok(trimmed.to_owned())
269}
270
271/// A filament material as a spool's registration or a slicer's settings name
272/// it, such as `PLA`: trimmed, and never blank. On the wire it is a string.
273#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
274#[serde(
275    crate = "printobserver_types::serde",
276    try_from = "String",
277    into = "String"
278)]
279pub struct MaterialName(String);
280
281impl JsonSchema for MaterialName {
282    fn schema_name() -> std::borrow::Cow<'static, str> {
283        std::borrow::Cow::Borrowed("MaterialName")
284    }
285
286    fn json_schema(
287        _generator: &mut printobserver_types::schemars::SchemaGenerator,
288    ) -> printobserver_types::schemars::Schema {
289        printobserver_types::schemars::json_schema!({
290            "type": "string",
291            "title": "MaterialName",
292            "description": "A filament material as a spool's registration or a slicer's settings name it, such as `PLA`: never blank, and trimmed of surrounding space as it is read.",
293            "minLength": 1,
294            "pattern": "\\S"
295        })
296    }
297}
298
299impl MaterialName {
300    /// The name, as text.
301    #[must_use]
302    pub fn as_str(&self) -> &str {
303        &self.0
304    }
305
306    /// Whether two names name one material: without regard to case.
307    #[must_use]
308    pub fn same(&self, other: &Self) -> bool {
309        self.0.to_lowercase() == other.0.to_lowercase()
310    }
311}
312
313impl TryFrom<String> for MaterialName {
314    type Error = String;
315
316    fn try_from(text: String) -> Result<Self, Self::Error> {
317        named_text(&text, "a material").map(Self)
318    }
319}
320
321impl From<MaterialName> for String {
322    fn from(name: MaterialName) -> Self {
323        name.0
324    }
325}
326
327impl core::fmt::Display for MaterialName {
328    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
329        formatter.write_str(&self.0)
330    }
331}
332
333/// A build sheet's identifier as the sheet table names it, such as
334/// `smooth-pei`: trimmed, and never blank. On the wire it is a string.
335#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
336#[serde(
337    crate = "printobserver_types::serde",
338    try_from = "String",
339    into = "String"
340)]
341pub struct SheetId(String);
342
343impl JsonSchema for SheetId {
344    fn schema_name() -> std::borrow::Cow<'static, str> {
345        std::borrow::Cow::Borrowed("SheetId")
346    }
347
348    fn json_schema(
349        _generator: &mut printobserver_types::schemars::SchemaGenerator,
350    ) -> printobserver_types::schemars::Schema {
351        printobserver_types::schemars::json_schema!({
352            "type": "string",
353            "title": "SheetId",
354            "description": "A build sheet's identifier as the sheet table names it, such as `smooth-pei`: never blank, and trimmed of surrounding space as it is read.",
355            "minLength": 1,
356            "pattern": "\\S"
357        })
358    }
359}
360
361impl SheetId {
362    /// The identifier, as text.
363    #[must_use]
364    pub fn as_str(&self) -> &str {
365        &self.0
366    }
367
368    /// Whether two identifiers name one sheet: without regard to case.
369    #[must_use]
370    pub fn same(&self, other: &Self) -> bool {
371        self.0.to_lowercase() == other.0.to_lowercase()
372    }
373}
374
375impl TryFrom<String> for SheetId {
376    type Error = String;
377
378    fn try_from(text: String) -> Result<Self, Self::Error> {
379        named_text(&text, "a sheet").map(Self)
380    }
381}
382
383impl From<SheetId> for String {
384    fn from(sheet: SheetId) -> Self {
385        sheet.0
386    }
387}
388
389impl core::fmt::Display for SheetId {
390    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
391        formatter.write_str(&self.0)
392    }
393}
394
395/// What the material check compared: the spool loaded on a tool and the
396/// material the file says that tool was sliced for.
397#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
398#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
399#[schemars(crate = "printobserver_types::schemars")]
400pub struct MaterialComparison {
401    /// The tool, in the printer's own numbering.
402    pub tool: i64,
403    /// The spool loaded on it.
404    pub spool: PreflightSpool,
405    /// That spool's material.
406    pub loaded: MaterialName,
407    /// The material the file's own `filament_type` names for the tool.
408    pub sliced_for: MaterialName,
409}
410
411/// A spool whose material the file could not be compared with.
412#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
413#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
414#[schemars(crate = "printobserver_types::schemars")]
415pub struct UncomparedMaterial {
416    /// The tool, in the printer's own numbering.
417    pub tool: i64,
418    /// The spool loaded on it.
419    pub spool: PreflightSpool,
420    /// That spool's material.
421    pub loaded: MaterialName,
422    /// The file that was to be compared.
423    pub file_name: FileName,
424}
425
426/// Why the material check objects to a start, with what it compared.
427#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
428#[serde(
429    crate = "printobserver_types::serde",
430    tag = "cause",
431    rename_all = "snake_case",
432    deny_unknown_fields
433)]
434#[schemars(crate = "printobserver_types::schemars")]
435pub enum MaterialObjection {
436    /// The file was sliced for another material than the loaded spool's.
437    Mismatch(MaterialComparison),
438    /// The file names no `filament_type`, so what it was sliced for is
439    /// unknown.
440    Undeclared(UncomparedMaterial),
441    /// The file's settings could not be read from the printer.
442    Unread {
443        /// The tool, in the printer's own numbering.
444        tool: i64,
445        /// The spool loaded on it.
446        spool: PreflightSpool,
447        /// That spool's material.
448        loaded: MaterialName,
449        /// The file whose settings could not be read.
450        file_name: FileName,
451        /// What the printer answered instead, in its own words.
452        detail: String,
453    },
454}
455
456/// Whether a file was sliced for the material of the spool loaded on tool 0,
457/// tagged by its verdict.
458#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
459#[serde(
460    crate = "printobserver_types::serde",
461    tag = "verdict",
462    rename_all = "snake_case",
463    deny_unknown_fields
464)]
465#[schemars(crate = "printobserver_types::schemars")]
466pub enum MaterialResult {
467    /// The file was sliced for the loaded spool's material.
468    Passed(MaterialComparison),
469    /// No tracked spool is loaded on tool 0, or the check is off, so nothing
470    /// was compared.
471    Unchecked,
472    /// The check refuses the start.
473    Refused {
474        /// What it objected to.
475        objection: MaterialObjection,
476    },
477    /// The start went ahead despite this objection, because an operator said
478    /// so.
479    Overridden {
480        /// What it objected to.
481        objection: MaterialObjection,
482    },
483    /// The check is set to warn, and let the start go ahead despite this
484    /// objection.
485    Warned {
486        /// What it objected to.
487        objection: MaterialObjection,
488    },
489}
490
491/// What the sheet check compared: the declared sheet, the loaded spool's
492/// material, and the sheets the table allows that material.
493#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
494#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
495#[schemars(crate = "printobserver_types::schemars")]
496pub struct SheetComparison {
497    /// The build sheet the manifest declares.
498    pub sheet: SheetId,
499    /// The material of the spool loaded on tool 0.
500    pub material: MaterialName,
501    /// Every sheet the table allows that material.
502    pub allowed: Vec<SheetId>,
503}
504
505/// Why the sheet check objects to a start, with what it compared.
506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
507#[serde(
508    crate = "printobserver_types::serde",
509    tag = "cause",
510    rename_all = "snake_case",
511    deny_unknown_fields
512)]
513#[schemars(crate = "printobserver_types::schemars")]
514pub enum SheetObjection {
515    /// The table lists the material, and not on this sheet.
516    NotAllowed(SheetComparison),
517    /// The table has no entry for the material.
518    UnlistedMaterial {
519        /// The build sheet the manifest declares.
520        sheet: SheetId,
521        /// The material of the spool loaded on tool 0.
522        material: MaterialName,
523    },
524    /// No entry of the table lists the sheet.
525    UnknownSheet {
526        /// The build sheet the manifest declares.
527        sheet: SheetId,
528        /// The material of the spool loaded on tool 0.
529        material: MaterialName,
530        /// Every sheet some entry lists.
531        known: Vec<SheetId>,
532    },
533}
534
535/// Whether the declared build sheet suits the loaded spool's material, tagged
536/// by its verdict.
537#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
538#[serde(
539    crate = "printobserver_types::serde",
540    tag = "verdict",
541    rename_all = "snake_case",
542    deny_unknown_fields
543)]
544#[schemars(crate = "printobserver_types::schemars")]
545pub enum SheetResult {
546    /// The table allows the material on the declared sheet.
547    Passed(SheetComparison),
548    /// No tracked spool is loaded on tool 0, or the check is off, so nothing
549    /// was compared.
550    Unchecked,
551    /// The manifest declares no sheet. This refuses every start, and no
552    /// override lets it through.
553    Undeclared,
554    /// The check refuses the start.
555    Refused {
556        /// What it objected to.
557        objection: SheetObjection,
558    },
559    /// The start went ahead despite this objection, because an operator said
560    /// so.
561    Overridden {
562        /// What it objected to.
563        objection: SheetObjection,
564    },
565    /// The check is set to warn, and let the start go ahead despite this
566    /// objection.
567    Warned {
568        /// What it objected to.
569        objection: SheetObjection,
570    },
571}