1use 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#[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 RecoverLift,
39 RecoverCool,
41 RecoverFan,
43 RecoverHeat,
45 RecoverPark,
47 RecoverHomeXy,
49 RecoverHomeZ,
51}
52
53impl RecoveryActionKind {
54 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 #[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 #[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#[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 RecoverLift {
113 mm: f64,
116 },
117 RecoverCool {},
119 RecoverFan {
121 percent: f64,
123 },
124 RecoverHeat {
126 tool: i64,
128 target_c: f64,
130 #[serde(default)]
133 #[schemars(extend("x-two-valued-fact" = true))]
134 clearance_asserted: bool,
135 },
136 RecoverPark {
138 #[serde(default)]
141 #[schemars(extend("x-two-valued-fact" = true))]
142 clearance_asserted: bool,
143 },
144 RecoverHomeXy {
146 #[serde(default)]
149 #[schemars(extend("x-two-valued-fact" = true))]
150 clearance_asserted: bool,
151 },
152 RecoverHomeZ {
154 #[serde(default)]
157 #[schemars(extend("x-two-valued-fact" = true))]
158 bed_clear_asserted: bool,
159 },
160}
161
162impl RecoveryAction {
163 #[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 #[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#[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 Mm,
202 Percent,
204 Tool,
206 TargetC,
208 ClearanceAsserted,
210 BedClearAsserted,
212}
213
214#[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 ActorMayNotRequest {
226 action: RecoveryActionKind,
228 },
229 PrintRunning {
232 state: PrinterState,
234 },
235 PrinterUnreachable,
237 ZUntrusted,
240 InsufficientClearance {
243 nozzle_z_mm: f64,
245 tallest_mm: f64,
247 margin_mm: f64,
249 },
250 OutOfBounds {
252 field: RecoveryField,
254 requested: f64,
256 allowed: Range,
258 },
259 AssertionRequired {
261 field: RecoveryField,
263 },
264 RecoveryNotConfigured,
267 PrinterCannot {
270 action: RecoveryActionKind,
272 detail: String,
274 },
275}
276
277#[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 ZPlus,
284 ZMinus,
286}
287
288#[derive(Debug, Clone, Copy, PartialEq)]
291pub struct RecoveryConfig {
292 pub away_from_bed: AwayFromBed,
294 pub max_z_mm: f64,
296 pub max_lift_mm: f64,
298 pub clearance_margin_mm: f64,
300 pub park_xy: [f64; 2],
302 pub z_home_xy: [f64; 2],
304 pub z_home_sweeps_bed: bool,
307}
308
309pub const DEFAULT_MAX_LIFT_MM: f64 = 50.0;
311
312pub const DEFAULT_CLEARANCE_MARGIN_MM: f64 = 5.0;
315
316#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct RecoveryGrants {
319 pub operator: Vec<RecoveryActionKind>,
321 pub agent: Vec<RecoveryActionKind>,
323 pub asserting: Vec<ActorClass>,
326}
327
328impl RecoveryGrants {
329 #[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 #[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 fn default() -> Self {
352 Self {
353 operator: RecoveryActionKind::ALL.to_vec(),
354 agent: Vec::new(),
355 asserting: vec![ActorClass::Operator],
356 }
357 }
358}
359
360fn 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#[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 TrustedSince(Timestamp),
393 Untrusted(String),
395}
396
397#[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 pub x: f64,
404 pub y: f64,
406 pub z: f64,
408}
409
410#[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 pub tool: i64,
417 pub actual_c: Option<f64>,
419 pub target_c: Option<f64>,
422}
423
424#[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 pub actual_c: Option<f64>,
431 pub target_c: Option<f64>,
434}
435
436#[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 pub tools: Vec<ToolTemperature>,
443 pub bed: Option<BedTemperature>,
445}
446
447#[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 pub print_id: PrintId,
455 pub tallest_mm: f64,
457 pub footprint: Footprint,
459}
460
461#[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 pub print_id: PrintId,
472 #[schemars(extend("x-two-valued-fact" = true))]
476 pub resumable: bool,
478}
479
480#[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 pub x: f64,
487 pub y: f64,
489 #[schemars(extend("x-two-valued-fact" = true))]
493 pub sweeps_bed: bool,
495}
496
497#[derive(Debug, Clone, PartialEq)]
500pub struct ActionAllowance {
501 pub action: RecoveryActionKind,
503 pub refusal: Option<RecoveryRejection>,
505}
506
507#[derive(Serialize, Deserialize)]
510#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
511struct AllowanceWire {
512 action: RecoveryActionKind,
514 allowed: bool,
517 #[serde(
520 default,
521 skip_serializing_if = "Option::is_none",
522 deserialize_with = "never_null"
523 )]
524 refusal: Option<RecoveryRejection>,
525}
526
527fn 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
556impl<'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
581impl 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 "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#[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 pub state: PrinterState,
631 pub z_trust: ZTrust,
633 pub position: Option<RecoveryPosition>,
636 pub temperatures: RecoveryTemperatures,
638 pub last_print: Option<LastPrint>,
641 pub paused_print: Option<PausedPrint>,
643 pub z_home: Option<ZHome>,
646 pub actions: Vec<ActionAllowance>,
648}
649
650#[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 Executed(ExecutionOutcome),
662 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}