Skip to main content

printobserver_core/records/
recovery.rs

1//! The closed vocabulary for moving the printer after a print fails, and what
2//! it is checked against.
3//!
4//! [`RecoveryAction`] is the whole of it: lifting the nozzle away from the bed,
5//! cooling every heater, setting the part fan, heating one tool, parking the
6//! head, homing X and Y, and homing Z. Like [`PrintAction`](super::PrintAction)
7//! it has no G-code field and no escape hatch; unlike it, it names no print,
8//! because what it moves is the printer whatever the last print left on its
9//! bed. Each request is refused with one [`RecoveryRejection`] or carried out,
10//! and either way is recorded with the printer's events.
11//!
12//! What a recovery is checked against is the printer's own facts —
13//! [`RecoveryConfig`], the operator's statement of the machine — and who may
14//! ask for which action, [`RecoveryGrants`]. Both are configuration rather
15//! than code.
16
17use printobserver_printer_api::{Footprint, PrinterState};
18use printobserver_types::contract::Sample;
19use printobserver_types::schemars::JsonSchema;
20use printobserver_types::serde::{Deserialize, Serialize};
21use printobserver_types::{PrintId, Range, Timestamp};
22
23use super::action::{ActorClass, ExecutionOutcome};
24
25/// One recovery action, named without its fields: what a grant names and what
26/// a refusal of an ungranted request names.
27#[derive(
28    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
29)]
30#[serde(
31    crate = "printobserver_types::serde",
32    rename_all = "snake_case",
33    deny_unknown_fields
34)]
35#[schemars(crate = "printobserver_types::schemars")]
36pub enum RecoveryActionKind {
37    /// Move the nozzle away from the bed.
38    RecoverLift,
39    /// Every heater's target to zero.
40    RecoverCool,
41    /// Set the part-cooling fan.
42    RecoverFan,
43    /// Heat one tool.
44    RecoverHeat,
45    /// Move the head to the configured park place.
46    RecoverPark,
47    /// Home X and Y.
48    RecoverHomeXy,
49    /// Home Z.
50    RecoverHomeZ,
51}
52
53impl RecoveryActionKind {
54    /// Every recovery action, in the order the vocabulary declares them.
55    pub const ALL: [Self; 7] = [
56        Self::RecoverLift,
57        Self::RecoverCool,
58        Self::RecoverFan,
59        Self::RecoverHeat,
60        Self::RecoverPark,
61        Self::RecoverHomeXy,
62        Self::RecoverHomeZ,
63    ];
64
65    /// The action's name, as the wire and its operation spell it.
66    #[must_use]
67    pub const fn as_str(self) -> &'static str {
68        match self {
69            Self::RecoverLift => "recover_lift",
70            Self::RecoverCool => "recover_cool",
71            Self::RecoverFan => "recover_fan",
72            Self::RecoverHeat => "recover_heat",
73            Self::RecoverPark => "recover_park",
74            Self::RecoverHomeXy => "recover_home_xy",
75            Self::RecoverHomeZ => "recover_home_z",
76        }
77    }
78
79    /// Whether this action moves the head across the bed or heats a nozzle
80    /// over it, and so needs Z trusted and the nozzle clear of the part.
81    #[must_use]
82    pub const fn needs_clearance(self) -> bool {
83        matches!(
84            self,
85            Self::RecoverHeat | Self::RecoverPark | Self::RecoverHomeXy
86        )
87    }
88}
89
90impl core::fmt::Display for RecoveryActionKind {
91    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
92        formatter.write_str(self.as_str())
93    }
94}
95
96/// The whole recovery vocabulary, and there is no other.
97///
98/// The two assertions are the operator's word for what printobserver cannot
99/// see: `clearance_asserted` that the nozzle is clear of the part, and
100/// `bed_clear_asserted` that homing Z will meet nothing on the bed. Each is
101/// false when left out.
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
103#[serde(
104    crate = "printobserver_types::serde",
105    tag = "action",
106    rename_all = "snake_case",
107    deny_unknown_fields
108)]
109#[schemars(crate = "printobserver_types::schemars")]
110pub enum RecoveryAction {
111    /// Move the nozzle away from the bed by `mm`.
112    RecoverLift {
113        /// How far, in millimetres: above zero and at most
114        /// `recovery.max_lift_mm`.
115        mm: f64,
116    },
117    /// Set every heater's target to zero.
118    RecoverCool {},
119    /// Set the part-cooling fan.
120    RecoverFan {
121        /// The percentage, from 0 to 100.
122        percent: f64,
123    },
124    /// Heat one tool, within the safety envelope's range for it.
125    RecoverHeat {
126        /// The tool, in the printer's own numbering.
127        tool: i64,
128        /// The target, in degrees Celsius.
129        target_c: f64,
130        /// The operator's word that the nozzle is clear of the part.
131        // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
132        #[serde(default)]
133        #[schemars(extend("x-two-valued-fact" = true))]
134        clearance_asserted: bool,
135    },
136    /// Move the head to `recovery.park_xy`.
137    RecoverPark {
138        /// The operator's word that the nozzle is clear of the part.
139        // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
140        #[serde(default)]
141        #[schemars(extend("x-two-valued-fact" = true))]
142        clearance_asserted: bool,
143    },
144    /// Home X and Y.
145    RecoverHomeXy {
146        /// The operator's word that the nozzle is clear of the part.
147        // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
148        #[serde(default)]
149        #[schemars(extend("x-two-valued-fact" = true))]
150        clearance_asserted: bool,
151    },
152    /// Home Z.
153    RecoverHomeZ {
154        /// The operator's word that homing Z will meet nothing on the bed.
155        // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
156        #[serde(default)]
157        #[schemars(extend("x-two-valued-fact" = true))]
158        bed_clear_asserted: bool,
159    },
160}
161
162impl RecoveryAction {
163    /// Which action this is, without its fields.
164    #[must_use]
165    pub const fn kind(&self) -> RecoveryActionKind {
166        match self {
167            Self::RecoverLift { .. } => RecoveryActionKind::RecoverLift,
168            Self::RecoverCool {} => RecoveryActionKind::RecoverCool,
169            Self::RecoverFan { .. } => RecoveryActionKind::RecoverFan,
170            Self::RecoverHeat { .. } => RecoveryActionKind::RecoverHeat,
171            Self::RecoverPark { .. } => RecoveryActionKind::RecoverPark,
172            Self::RecoverHomeXy { .. } => RecoveryActionKind::RecoverHomeXy,
173            Self::RecoverHomeZ { .. } => RecoveryActionKind::RecoverHomeZ,
174        }
175    }
176
177    /// Whether the request carries the operator's word that the nozzle is
178    /// clear of the part.
179    #[must_use]
180    pub const fn clearance_asserted(&self) -> bool {
181        match self {
182            Self::RecoverHeat {
183                clearance_asserted, ..
184            }
185            | Self::RecoverPark { clearance_asserted }
186            | Self::RecoverHomeXy { clearance_asserted } => *clearance_asserted,
187            Self::RecoverLift { .. }
188            | Self::RecoverCool {}
189            | Self::RecoverFan { .. }
190            | Self::RecoverHomeZ { .. } => false,
191        }
192    }
193}
194
195/// One field of a recovery action a bound is held to.
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
197#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
198#[schemars(crate = "printobserver_types::schemars")]
199pub enum RecoveryField {
200    /// A lift's distance, in millimetres.
201    Mm,
202    /// The fan's percentage.
203    Percent,
204    /// A heat's tool.
205    Tool,
206    /// A heat's target, in degrees Celsius.
207    TargetC,
208    /// The operator's word that the nozzle is clear of the part.
209    ClearanceAsserted,
210    /// The operator's word that homing Z will meet nothing on the bed.
211    BedClearAsserted,
212}
213
214/// Why a recovery request was refused, each a variant of its own so a
215/// consumer tells them apart by matching rather than by reading words.
216#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
217#[serde(
218    crate = "printobserver_types::serde",
219    rename_all = "snake_case",
220    deny_unknown_fields
221)]
222#[schemars(crate = "printobserver_types::schemars")]
223pub enum RecoveryRejection {
224    /// The asking actor's class is not granted this action.
225    ActorMayNotRequest {
226        /// The action asked for.
227        action: RecoveryActionKind,
228    },
229    /// A print is running, or being cancelled: nothing may move the printer
230    /// under it.
231    PrintRunning {
232        /// The state the printer reported.
233        state: PrinterState,
234    },
235    /// The printer could not be read, or reports itself offline or in error.
236    PrinterUnreachable,
237    /// Nothing printobserver did has told it where Z is, so no move that
238    /// depends on the nozzle's height above the part may be made.
239    ZUntrusted,
240    /// The nozzle is not far enough above the tallest part the last print
241    /// laid down.
242    InsufficientClearance {
243        /// Where the printer reports the nozzle, in millimetres.
244        nozzle_z_mm: f64,
245        /// The tallest part the last print laid down, in millimetres.
246        tallest_mm: f64,
247        /// The clearance asked above it, in millimetres.
248        margin_mm: f64,
249    },
250    /// A value the request carries is outside the range allowed for it.
251    OutOfBounds {
252        /// The field.
253        field: RecoveryField,
254        /// The value asked for.
255        requested: f64,
256        /// The range allowed, inclusive.
257        allowed: Range,
258    },
259    /// This action needs an assertion the request did not make.
260    AssertionRequired {
261        /// The assertion it needs.
262        field: RecoveryField,
263    },
264    /// The configuration states nothing of this printer's recovery facts, so
265    /// no recovery action can be checked.
266    RecoveryNotConfigured,
267    /// The printer cannot do what this action needs: a move its adapter does
268    /// not support, or a nozzle position it cannot read.
269    PrinterCannot {
270        /// The action asked for.
271        action: RecoveryActionKind,
272        /// What the printer cannot do, in words.
273        detail: String,
274    },
275}
276
277/// Which way along Z moves the nozzle away from the bed.
278#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
279#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
280#[schemars(crate = "printobserver_types::schemars")]
281pub enum AwayFromBed {
282    /// Up the axis: Z increasing.
283    ZPlus,
284    /// Down the axis: Z decreasing.
285    ZMinus,
286}
287
288/// The printer's own facts a recovery is checked against, as the operator
289/// states them.
290#[derive(Debug, Clone, Copy, PartialEq)]
291pub struct RecoveryConfig {
292    /// Which way along Z moves the nozzle away from the bed.
293    pub away_from_bed: AwayFromBed,
294    /// The highest Z the machine can reach, in millimetres.
295    pub max_z_mm: f64,
296    /// The longest lift one request may ask for, in millimetres.
297    pub max_lift_mm: f64,
298    /// How far above the tallest part the nozzle must be, in millimetres.
299    pub clearance_margin_mm: f64,
300    /// Where the head is parked, in X and Y.
301    pub park_xy: [f64; 2],
302    /// Where in X and Y the machine homes Z.
303    pub z_home_xy: [f64; 2],
304    /// Whether homing Z brings a gantry down over the whole bed.
305    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
306    pub z_home_sweeps_bed: bool,
307}
308
309/// The lift a request may ask for when nothing configures it, in millimetres.
310pub const DEFAULT_MAX_LIFT_MM: f64 = 50.0;
311
312/// The clearance asked above the tallest part when nothing configures it, in
313/// millimetres.
314pub const DEFAULT_CLEARANCE_MARGIN_MM: f64 = 5.0;
315
316/// Who may ask for which recovery action, and whose assertions count.
317#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct RecoveryGrants {
319    /// The actions the operator may ask for.
320    pub operator: Vec<RecoveryActionKind>,
321    /// The actions the agent may ask for.
322    pub agent: Vec<RecoveryActionKind>,
323    /// The actor classes whose word that the nozzle or the bed is clear
324    /// counts. The agent is never among them.
325    pub asserting: Vec<ActorClass>,
326}
327
328impl RecoveryGrants {
329    /// Whether one actor class may ask for one action. The system asks for
330    /// none.
331    #[must_use]
332    pub fn grants(&self, class: ActorClass, action: RecoveryActionKind) -> bool {
333        match class {
334            ActorClass::Operator => self.operator.contains(&action),
335            ActorClass::Agent => self.agent.contains(&action),
336            ActorClass::System => false,
337        }
338    }
339
340    /// Whether one actor class's assertion counts. The agent's never does:
341    /// an assertion is a person's word for what they can see.
342    #[must_use]
343    pub fn assertion_counts(&self, class: ActorClass) -> bool {
344        class != ActorClass::Agent && self.asserting.contains(&class)
345    }
346}
347
348impl Default for RecoveryGrants {
349    /// The operator holds every action, and the agent none; only the
350    /// operator's assertions count.
351    fn default() -> Self {
352        Self {
353            operator: RecoveryActionKind::ALL.to_vec(),
354            agent: Vec::new(),
355            asserting: vec![ActorClass::Operator],
356        }
357    }
358}
359
360/// Declare every field of a shape required, as the null it may be: these
361/// shapes send each field always, `null` where there is nothing to report,
362/// and the derive would otherwise read an `Option` as a field that may be
363/// absent.
364fn every_field_is_sent(schema: &mut printobserver_types::schemars::Schema) {
365    let named: Vec<printobserver_types::serde_json::Value> = schema
366        .get("properties")
367        .and_then(printobserver_types::serde_json::Value::as_object)
368        .map(|properties| {
369            properties
370                .keys()
371                .map(|name| printobserver_types::serde_json::Value::from(name.as_str()))
372                .collect()
373        })
374        .unwrap_or_default();
375    schema.insert(
376        "required".to_owned(),
377        printobserver_types::serde_json::Value::Array(named),
378    );
379}
380
381/// Whether Z is trusted, and since when or why not.
382#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
383#[serde(
384    crate = "printobserver_types::serde",
385    rename_all = "snake_case",
386    deny_unknown_fields
387)]
388#[schemars(crate = "printobserver_types::schemars")]
389pub enum ZTrust {
390    /// Z is where printobserver last put it, from this instant on: a `home_z`
391    /// it executed, or a print it started.
392    TrustedSince(Timestamp),
393    /// Z is not trusted, and why.
394    Untrusted(String),
395}
396
397/// Where the print head is, in millimetres, as the printer reported it.
398#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
399#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
400#[schemars(crate = "printobserver_types::schemars")]
401pub struct RecoveryPosition {
402    /// X.
403    pub x: f64,
404    /// Y.
405    pub y: f64,
406    /// Z.
407    pub z: f64,
408}
409
410/// One tool heater, as a recovery read reports it.
411#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
412#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
413#[schemars(crate = "printobserver_types::schemars", transform = every_field_is_sent)]
414pub struct ToolTemperature {
415    /// The tool, in the printer's own numbering.
416    pub tool: i64,
417    /// What it reads, in degrees Celsius, `null` when not reported.
418    pub actual_c: Option<f64>,
419    /// What it is driving towards, in degrees Celsius, `null` when not
420    /// reported.
421    pub target_c: Option<f64>,
422}
423
424/// The bed heater, as a recovery read reports it.
425#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
426#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
427#[schemars(crate = "printobserver_types::schemars", transform = every_field_is_sent)]
428pub struct BedTemperature {
429    /// What it reads, in degrees Celsius, `null` when not reported.
430    pub actual_c: Option<f64>,
431    /// What it is driving towards, in degrees Celsius, `null` when not
432    /// reported.
433    pub target_c: Option<f64>,
434}
435
436/// Every heater, as a recovery read reports it.
437#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
438#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
439#[schemars(crate = "printobserver_types::schemars", transform = every_field_is_sent)]
440pub struct RecoveryTemperatures {
441    /// Each tool.
442    pub tools: Vec<ToolTemperature>,
443    /// The bed, `null` when the printer reports none.
444    pub bed: Option<BedTemperature>,
445}
446
447/// What the last print laid down, read from its own G-code up to the last
448/// file position recorded for it.
449#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
450#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
451#[schemars(crate = "printobserver_types::schemars")]
452pub struct LastPrint {
453    /// The print.
454    pub print_id: PrintId,
455    /// The tallest part it laid down, in millimetres.
456    pub tallest_mm: f64,
457    /// Where in X and Y it laid material.
458    pub footprint: Footprint,
459}
460
461/// The print paused under the printer, and whether resuming it is still safe.
462///
463/// A recovery action executed while it was paused moved the head, and
464/// `OctoPrint` restores no position on resume, so the rest of the layer would
465/// print at the wrong height: such a print is not resumable.
466#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
467#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
468#[schemars(crate = "printobserver_types::schemars")]
469pub struct PausedPrint {
470    /// The print.
471    pub print_id: PrintId,
472    /// Whether it may be resumed.
473    // Marked as a two-valued fact, so a client generated from it carries this
474    // directive and its reason too.
475    #[schemars(extend("x-two-valued-fact" = true))]
476    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
477    pub resumable: bool,
478}
479
480/// Where the machine homes Z, and whether doing so sweeps the bed.
481#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
482#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
483#[schemars(crate = "printobserver_types::schemars")]
484pub struct ZHome {
485    /// Where in X Z is homed, in millimetres.
486    pub x: f64,
487    /// Where in Y Z is homed, in millimetres.
488    pub y: f64,
489    /// Whether homing Z brings a gantry down over the whole bed.
490    // Marked as a two-valued fact, so a client generated from it carries this
491    // directive and its reason too.
492    #[schemars(extend("x-two-valued-fact" = true))]
493    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
494    pub sweeps_bed: bool,
495}
496
497/// Whether one recovery action is allowed now, and the refusal it would meet
498/// when it is not.
499#[derive(Debug, Clone, PartialEq)]
500pub struct ActionAllowance {
501    /// The action.
502    pub action: RecoveryActionKind,
503    /// Its refusal, absent when it is allowed.
504    pub refusal: Option<RecoveryRejection>,
505}
506
507/// The wire form of [`ActionAllowance`]: `allowed`, and a refusal exactly when
508/// it is false.
509#[derive(Serialize, Deserialize)]
510#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
511struct AllowanceWire {
512    /// The action.
513    action: RecoveryActionKind,
514    /// Whether it is allowed now.
515    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
516    allowed: bool,
517    /// Its refusal, present exactly when it is not allowed, and never sent
518    /// as null: a null is refused as it is read rather than taken for absence.
519    #[serde(
520        default,
521        skip_serializing_if = "Option::is_none",
522        deserialize_with = "never_null"
523    )]
524    refusal: Option<RecoveryRejection>,
525}
526
527/// A field that was sent, which a null is not.
528fn never_null<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
529where
530    D: printobserver_types::serde::Deserializer<'de>,
531    T: Deserialize<'de>,
532{
533    Option::<T>::deserialize(deserializer)?
534        .map(Some)
535        .ok_or_else(|| {
536            printobserver_types::serde::de::Error::custom(
537                "a refusal is sent as one or not at all, never as null",
538            )
539        })
540}
541
542impl Serialize for ActionAllowance {
543    fn serialize<S: printobserver_types::serde::Serializer>(
544        &self,
545        serializer: S,
546    ) -> Result<S::Ok, S::Error> {
547        AllowanceWire {
548            action: self.action,
549            allowed: self.refusal.is_none(),
550            refusal: self.refusal.clone(),
551        }
552        .serialize(serializer)
553    }
554}
555
556// llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
557impl<'de> Deserialize<'de> for ActionAllowance {
558    fn deserialize<D: printobserver_types::serde::Deserializer<'de>>(
559        deserializer: D,
560    ) -> Result<Self, D::Error> {
561        let wire = AllowanceWire::deserialize(deserializer)?;
562        match (wire.allowed, wire.refusal) {
563            (true, None) => Ok(Self {
564                action: wire.action,
565                refusal: None,
566            }),
567            (false, Some(refusal)) => Ok(Self {
568                action: wire.action,
569                refusal: Some(refusal),
570            }),
571            (true, Some(_)) => Err(printobserver_types::serde::de::Error::custom(
572                "an allowed action carries no refusal",
573            )),
574            (false, None) => Err(printobserver_types::serde::de::Error::custom(
575                "a refused action carries its refusal",
576            )),
577        }
578    }
579}
580
581/// The schema is the wire form's own object: `allowed`, and `refusal` present
582/// exactly when it is false — stated in the schema itself, and held to the
583/// same verdicts as reading one back by `tests/records.rs`.
584impl JsonSchema for ActionAllowance {
585    fn schema_name() -> std::borrow::Cow<'static, str> {
586        std::borrow::Cow::Borrowed("ActionAllowance")
587    }
588
589    fn json_schema(
590        generator: &mut printobserver_types::schemars::SchemaGenerator,
591    ) -> printobserver_types::schemars::Schema {
592        let to_value = |schema: printobserver_types::schemars::Schema| {
593            printobserver_types::serde_json::to_value(schema).unwrap_or_default()
594        };
595        let action = to_value(generator.subschema_for::<RecoveryActionKind>());
596        let refusal = to_value(generator.subschema_for::<RecoveryRejection>());
597        let schema = printobserver_types::serde_json::json!({
598            "title": "ActionAllowance",
599            "description": "Whether one recovery action is allowed now: `allowed`, and the \
600                refusal it would meet, present exactly when it is not.",
601            "type": "object",
602            "properties": {
603                "action": action,
604                "allowed": {
605                    "type": "boolean",
606                    "description": "Whether it is allowed now.",
607                    "x-paired-with": "refusal",
608                },
609                "refusal": refusal,
610            },
611            "required": ["action", "allowed"],
612            "additionalProperties": false,
613            // The pairing its reading holds it to: a refused action carries
614            // its refusal, and an allowed one carries none.
615            "if": { "properties": { "allowed": { "const": false } } },
616            "then": { "required": ["refusal"] },
617            "else": { "not": { "required": ["refusal"] } },
618        });
619        printobserver_types::schemars::Schema::try_from(schema).unwrap_or_default()
620    }
621}
622
623/// What a recovery read answers: everything a recovery is checked against,
624/// and what each action would meet now.
625#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
626#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
627#[schemars(crate = "printobserver_types::schemars", transform = every_field_is_sent)]
628pub struct RecoveryStatus {
629    /// The state the printer reports; `offline` when it could not be read.
630    pub state: PrinterState,
631    /// Whether Z is trusted.
632    pub z_trust: ZTrust,
633    /// Where the head is, read only while Z is trusted; `null` otherwise or
634    /// when it could not be read.
635    pub position: Option<RecoveryPosition>,
636    /// Every heater.
637    pub temperatures: RecoveryTemperatures,
638    /// What the last print laid down, `null` when there is no print with a
639    /// file to read or its file could not be read.
640    pub last_print: Option<LastPrint>,
641    /// The print paused under the printer, `null` when none is.
642    pub paused_print: Option<PausedPrint>,
643    /// Where Z is homed and whether that sweeps the bed, `null` when
644    /// recovery is not configured.
645    pub z_home: Option<ZHome>,
646    /// Each action, and whether it is allowed now.
647    pub actions: Vec<ActionAllowance>,
648}
649
650/// What became of a recovery request: carried out with the printer's outcome,
651/// or refused — one or the other, never both and never neither.
652#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
653#[serde(
654    crate = "printobserver_types::serde",
655    rename_all = "snake_case",
656    deny_unknown_fields
657)]
658#[schemars(crate = "printobserver_types::schemars")]
659pub enum RecoveryDecision {
660    /// It reached the printer, and this is what the printer made of it.
661    Executed(ExecutionOutcome),
662    /// It was refused, and reached nothing.
663    Rejected(RecoveryRejection),
664}
665
666impl Sample for RecoveryActionKind {
667    fn sample_full() -> Self {
668        Self::RecoverLift
669    }
670}
671
672impl Sample for RecoveryAction {
673    fn sample_full() -> Self {
674        Self::RecoverHeat {
675            tool: 0,
676            target_c: 180.0,
677            clearance_asserted: true,
678        }
679    }
680
681    fn sample_minimal() -> Self {
682        Self::RecoverCool {}
683    }
684
685    fn sample_alternates() -> Vec<Self> {
686        vec![
687            Self::RecoverLift { mm: 10.0 },
688            Self::RecoverFan { percent: 50.0 },
689            Self::RecoverPark {
690                clearance_asserted: false,
691            },
692            Self::RecoverHomeXy {
693                clearance_asserted: false,
694            },
695            Self::RecoverHomeZ {
696                bed_clear_asserted: true,
697            },
698        ]
699    }
700}
701
702impl Sample for RecoveryField {
703    fn sample_full() -> Self {
704        Self::Mm
705    }
706}
707
708impl Sample for RecoveryRejection {
709    fn sample_full() -> Self {
710        Self::InsufficientClearance {
711            nozzle_z_mm: 3.0,
712            tallest_mm: 6.0,
713            margin_mm: 5.0,
714        }
715    }
716
717    fn sample_minimal() -> Self {
718        Self::ZUntrusted
719    }
720
721    fn sample_alternates() -> Vec<Self> {
722        vec![
723            Self::ActorMayNotRequest {
724                action: RecoveryActionKind::RecoverHomeZ,
725            },
726            Self::PrintRunning {
727                state: PrinterState::Printing,
728            },
729            Self::PrinterUnreachable,
730            Self::OutOfBounds {
731                field: RecoveryField::Mm,
732                requested: 80.0,
733                allowed: Range::new(0.0, 50.0),
734            },
735            Self::AssertionRequired {
736                field: RecoveryField::BedClearAsserted,
737            },
738            Self::RecoveryNotConfigured,
739            Self::PrinterCannot {
740                action: RecoveryActionKind::RecoverPark,
741                detail: "this printer cannot move its head to a place".to_owned(),
742            },
743        ]
744    }
745}
746
747impl Sample for ZTrust {
748    fn sample_full() -> Self {
749        Self::TrustedSince(Timestamp::sample_full())
750    }
751
752    fn sample_minimal() -> Self {
753        Self::Untrusted("the server started, and has homed no Z since".to_owned())
754    }
755}
756
757impl Sample for RecoveryPosition {
758    fn sample_full() -> Self {
759        Self {
760            x: 100.0,
761            y: 100.0,
762            z: 12.0,
763        }
764    }
765}
766
767impl Sample for ToolTemperature {
768    fn sample_full() -> Self {
769        Self {
770            tool: 0,
771            actual_c: Some(180.0),
772            target_c: Some(180.0),
773        }
774    }
775
776    fn sample_minimal() -> Self {
777        Self {
778            tool: 0,
779            actual_c: None,
780            target_c: None,
781        }
782    }
783}
784
785impl Sample for BedTemperature {
786    fn sample_full() -> Self {
787        Self {
788            actual_c: Some(60.0),
789            target_c: Some(0.0),
790        }
791    }
792
793    fn sample_minimal() -> Self {
794        Self {
795            actual_c: None,
796            target_c: None,
797        }
798    }
799}
800
801impl Sample for RecoveryTemperatures {
802    fn sample_full() -> Self {
803        Self {
804            tools: vec![ToolTemperature::sample_full()],
805            bed: Some(BedTemperature::sample_full()),
806        }
807    }
808
809    fn sample_minimal() -> Self {
810        Self {
811            tools: Vec::new(),
812            bed: None,
813        }
814    }
815}
816
817impl Sample for LastPrint {
818    fn sample_full() -> Self {
819        Self {
820            print_id: PrintId::sample_full(),
821            tallest_mm: 6.0,
822            footprint: Footprint::sample_full(),
823        }
824    }
825}
826
827impl Sample for PausedPrint {
828    fn sample_full() -> Self {
829        Self {
830            print_id: PrintId::sample_full(),
831            resumable: false,
832        }
833    }
834}
835
836impl Sample for ZHome {
837    fn sample_full() -> Self {
838        Self {
839            x: 125.0,
840            y: 105.0,
841            sweeps_bed: true,
842        }
843    }
844}
845
846impl Sample for ActionAllowance {
847    fn sample_full() -> Self {
848        Self {
849            action: RecoveryActionKind::RecoverPark,
850            refusal: Some(RecoveryRejection::ZUntrusted),
851        }
852    }
853
854    fn sample_minimal() -> Self {
855        Self {
856            action: RecoveryActionKind::RecoverLift,
857            refusal: None,
858        }
859    }
860}
861
862impl Sample for RecoveryStatus {
863    fn sample_full() -> Self {
864        Self {
865            state: PrinterState::Paused,
866            z_trust: ZTrust::sample_full(),
867            position: Some(RecoveryPosition::sample_full()),
868            temperatures: RecoveryTemperatures::sample_full(),
869            last_print: Some(LastPrint::sample_full()),
870            paused_print: Some(PausedPrint::sample_full()),
871            z_home: Some(ZHome::sample_full()),
872            actions: vec![
873                ActionAllowance::sample_minimal(),
874                ActionAllowance::sample_full(),
875            ],
876        }
877    }
878
879    fn sample_minimal() -> Self {
880        Self {
881            state: PrinterState::Operational,
882            z_trust: ZTrust::sample_minimal(),
883            position: None,
884            temperatures: RecoveryTemperatures::sample_minimal(),
885            last_print: None,
886            paused_print: None,
887            z_home: None,
888            actions: Vec::new(),
889        }
890    }
891}
892
893impl Sample for RecoveryDecision {
894    fn sample_full() -> Self {
895        Self::Rejected(RecoveryRejection::sample_full())
896    }
897
898    fn sample_alternates() -> Vec<Self> {
899        vec![
900            Self::Executed(ExecutionOutcome::Succeeded),
901            Self::Executed(ExecutionOutcome::Failed {
902                reason: "the printer refused the request with 409: Printer is busy".to_owned(),
903            }),
904        ]
905    }
906}