use printobserver_printer_api::{Footprint, PrinterState};
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{PrintId, Range, Timestamp};
use super::action::{ActorClass, ExecutionOutcome};
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
#[serde(
crate = "printobserver_types::serde",
rename_all = "snake_case",
deny_unknown_fields
)]
#[schemars(crate = "printobserver_types::schemars")]
pub enum RecoveryActionKind {
RecoverLift,
RecoverCool,
RecoverFan,
RecoverHeat,
RecoverPark,
RecoverHomeXy,
RecoverHomeZ,
}
impl RecoveryActionKind {
pub const ALL: [Self; 7] = [
Self::RecoverLift,
Self::RecoverCool,
Self::RecoverFan,
Self::RecoverHeat,
Self::RecoverPark,
Self::RecoverHomeXy,
Self::RecoverHomeZ,
];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::RecoverLift => "recover_lift",
Self::RecoverCool => "recover_cool",
Self::RecoverFan => "recover_fan",
Self::RecoverHeat => "recover_heat",
Self::RecoverPark => "recover_park",
Self::RecoverHomeXy => "recover_home_xy",
Self::RecoverHomeZ => "recover_home_z",
}
}
#[must_use]
pub const fn needs_clearance(self) -> bool {
matches!(
self,
Self::RecoverHeat | Self::RecoverPark | Self::RecoverHomeXy
)
}
}
impl core::fmt::Display for RecoveryActionKind {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
tag = "action",
rename_all = "snake_case",
deny_unknown_fields
)]
#[schemars(crate = "printobserver_types::schemars")]
pub enum RecoveryAction {
RecoverLift {
mm: f64,
},
RecoverCool {},
RecoverFan {
percent: f64,
},
RecoverHeat {
tool: i64,
target_c: f64,
#[serde(default)]
#[schemars(extend("x-two-valued-fact" = true))]
clearance_asserted: bool,
},
RecoverPark {
#[serde(default)]
#[schemars(extend("x-two-valued-fact" = true))]
clearance_asserted: bool,
},
RecoverHomeXy {
#[serde(default)]
#[schemars(extend("x-two-valued-fact" = true))]
clearance_asserted: bool,
},
RecoverHomeZ {
#[serde(default)]
#[schemars(extend("x-two-valued-fact" = true))]
bed_clear_asserted: bool,
},
}
impl RecoveryAction {
#[must_use]
pub const fn kind(&self) -> RecoveryActionKind {
match self {
Self::RecoverLift { .. } => RecoveryActionKind::RecoverLift,
Self::RecoverCool {} => RecoveryActionKind::RecoverCool,
Self::RecoverFan { .. } => RecoveryActionKind::RecoverFan,
Self::RecoverHeat { .. } => RecoveryActionKind::RecoverHeat,
Self::RecoverPark { .. } => RecoveryActionKind::RecoverPark,
Self::RecoverHomeXy { .. } => RecoveryActionKind::RecoverHomeXy,
Self::RecoverHomeZ { .. } => RecoveryActionKind::RecoverHomeZ,
}
}
#[must_use]
pub const fn clearance_asserted(&self) -> bool {
match self {
Self::RecoverHeat {
clearance_asserted, ..
}
| Self::RecoverPark { clearance_asserted }
| Self::RecoverHomeXy { clearance_asserted } => *clearance_asserted,
Self::RecoverLift { .. }
| Self::RecoverCool {}
| Self::RecoverFan { .. }
| Self::RecoverHomeZ { .. } => false,
}
}
}
#[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 RecoveryField {
Mm,
Percent,
Tool,
TargetC,
ClearanceAsserted,
BedClearAsserted,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
rename_all = "snake_case",
deny_unknown_fields
)]
#[schemars(crate = "printobserver_types::schemars")]
pub enum RecoveryRejection {
ActorMayNotRequest {
action: RecoveryActionKind,
},
PrintRunning {
state: PrinterState,
},
PrinterUnreachable,
ZUntrusted,
InsufficientClearance {
nozzle_z_mm: f64,
tallest_mm: f64,
margin_mm: f64,
},
OutOfBounds {
field: RecoveryField,
requested: f64,
allowed: Range,
},
AssertionRequired {
field: RecoveryField,
},
RecoveryNotConfigured,
PrinterCannot {
action: RecoveryActionKind,
detail: String,
},
}
#[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 AwayFromBed {
ZPlus,
ZMinus,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RecoveryConfig {
pub away_from_bed: AwayFromBed,
pub max_z_mm: f64,
pub max_lift_mm: f64,
pub clearance_margin_mm: f64,
pub park_xy: [f64; 2],
pub z_home_xy: [f64; 2],
pub z_home_sweeps_bed: bool,
}
pub const DEFAULT_MAX_LIFT_MM: f64 = 50.0;
pub const DEFAULT_CLEARANCE_MARGIN_MM: f64 = 5.0;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecoveryGrants {
pub operator: Vec<RecoveryActionKind>,
pub agent: Vec<RecoveryActionKind>,
pub asserting: Vec<ActorClass>,
}
impl RecoveryGrants {
#[must_use]
pub fn grants(&self, class: ActorClass, action: RecoveryActionKind) -> bool {
match class {
ActorClass::Operator => self.operator.contains(&action),
ActorClass::Agent => self.agent.contains(&action),
ActorClass::System => false,
}
}
#[must_use]
pub fn assertion_counts(&self, class: ActorClass) -> bool {
class != ActorClass::Agent && self.asserting.contains(&class)
}
}
impl Default for RecoveryGrants {
fn default() -> Self {
Self {
operator: RecoveryActionKind::ALL.to_vec(),
agent: Vec::new(),
asserting: vec![ActorClass::Operator],
}
}
}
fn every_field_is_sent(schema: &mut printobserver_types::schemars::Schema) {
let named: Vec<printobserver_types::serde_json::Value> = schema
.get("properties")
.and_then(printobserver_types::serde_json::Value::as_object)
.map(|properties| {
properties
.keys()
.map(|name| printobserver_types::serde_json::Value::from(name.as_str()))
.collect()
})
.unwrap_or_default();
schema.insert(
"required".to_owned(),
printobserver_types::serde_json::Value::Array(named),
);
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
rename_all = "snake_case",
deny_unknown_fields
)]
#[schemars(crate = "printobserver_types::schemars")]
pub enum ZTrust {
TrustedSince(Timestamp),
Untrusted(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct RecoveryPosition {
pub x: f64,
pub y: f64,
pub z: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars", transform = every_field_is_sent)]
pub struct ToolTemperature {
pub tool: i64,
pub actual_c: Option<f64>,
pub target_c: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars", transform = every_field_is_sent)]
pub struct BedTemperature {
pub actual_c: Option<f64>,
pub target_c: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars", transform = every_field_is_sent)]
pub struct RecoveryTemperatures {
pub tools: Vec<ToolTemperature>,
pub bed: Option<BedTemperature>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct LastPrint {
pub print_id: PrintId,
pub tallest_mm: f64,
pub footprint: Footprint,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct PausedPrint {
pub print_id: PrintId,
#[schemars(extend("x-two-valued-fact" = true))]
pub resumable: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ZHome {
pub x: f64,
pub y: f64,
#[schemars(extend("x-two-valued-fact" = true))]
pub sweeps_bed: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ActionAllowance {
pub action: RecoveryActionKind,
pub refusal: Option<RecoveryRejection>,
}
#[derive(Serialize, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
struct AllowanceWire {
action: RecoveryActionKind,
allowed: bool,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "never_null"
)]
refusal: Option<RecoveryRejection>,
}
fn never_null<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: printobserver_types::serde::Deserializer<'de>,
T: Deserialize<'de>,
{
Option::<T>::deserialize(deserializer)?
.map(Some)
.ok_or_else(|| {
printobserver_types::serde::de::Error::custom(
"a refusal is sent as one or not at all, never as null",
)
})
}
impl Serialize for ActionAllowance {
fn serialize<S: printobserver_types::serde::Serializer>(
&self,
serializer: S,
) -> Result<S::Ok, S::Error> {
AllowanceWire {
action: self.action,
allowed: self.refusal.is_none(),
refusal: self.refusal.clone(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ActionAllowance {
fn deserialize<D: printobserver_types::serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Self, D::Error> {
let wire = AllowanceWire::deserialize(deserializer)?;
match (wire.allowed, wire.refusal) {
(true, None) => Ok(Self {
action: wire.action,
refusal: None,
}),
(false, Some(refusal)) => Ok(Self {
action: wire.action,
refusal: Some(refusal),
}),
(true, Some(_)) => Err(printobserver_types::serde::de::Error::custom(
"an allowed action carries no refusal",
)),
(false, None) => Err(printobserver_types::serde::de::Error::custom(
"a refused action carries its refusal",
)),
}
}
}
impl JsonSchema for ActionAllowance {
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("ActionAllowance")
}
fn json_schema(
generator: &mut printobserver_types::schemars::SchemaGenerator,
) -> printobserver_types::schemars::Schema {
let to_value = |schema: printobserver_types::schemars::Schema| {
printobserver_types::serde_json::to_value(schema).unwrap_or_default()
};
let action = to_value(generator.subschema_for::<RecoveryActionKind>());
let refusal = to_value(generator.subschema_for::<RecoveryRejection>());
let schema = printobserver_types::serde_json::json!({
"title": "ActionAllowance",
"description": "Whether one recovery action is allowed now: `allowed`, and the \
refusal it would meet, present exactly when it is not.",
"type": "object",
"properties": {
"action": action,
"allowed": {
"type": "boolean",
"description": "Whether it is allowed now.",
"x-paired-with": "refusal",
},
"refusal": refusal,
},
"required": ["action", "allowed"],
"additionalProperties": false,
"if": { "properties": { "allowed": { "const": false } } },
"then": { "required": ["refusal"] },
"else": { "not": { "required": ["refusal"] } },
});
printobserver_types::schemars::Schema::try_from(schema).unwrap_or_default()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars", transform = every_field_is_sent)]
pub struct RecoveryStatus {
pub state: PrinterState,
pub z_trust: ZTrust,
pub position: Option<RecoveryPosition>,
pub temperatures: RecoveryTemperatures,
pub last_print: Option<LastPrint>,
pub paused_print: Option<PausedPrint>,
pub z_home: Option<ZHome>,
pub actions: Vec<ActionAllowance>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
rename_all = "snake_case",
deny_unknown_fields
)]
#[schemars(crate = "printobserver_types::schemars")]
pub enum RecoveryDecision {
Executed(ExecutionOutcome),
Rejected(RecoveryRejection),
}
impl Sample for RecoveryActionKind {
fn sample_full() -> Self {
Self::RecoverLift
}
}
impl Sample for RecoveryAction {
fn sample_full() -> Self {
Self::RecoverHeat {
tool: 0,
target_c: 180.0,
clearance_asserted: true,
}
}
fn sample_minimal() -> Self {
Self::RecoverCool {}
}
fn sample_alternates() -> Vec<Self> {
vec![
Self::RecoverLift { mm: 10.0 },
Self::RecoverFan { percent: 50.0 },
Self::RecoverPark {
clearance_asserted: false,
},
Self::RecoverHomeXy {
clearance_asserted: false,
},
Self::RecoverHomeZ {
bed_clear_asserted: true,
},
]
}
}
impl Sample for RecoveryField {
fn sample_full() -> Self {
Self::Mm
}
}
impl Sample for RecoveryRejection {
fn sample_full() -> Self {
Self::InsufficientClearance {
nozzle_z_mm: 3.0,
tallest_mm: 6.0,
margin_mm: 5.0,
}
}
fn sample_minimal() -> Self {
Self::ZUntrusted
}
fn sample_alternates() -> Vec<Self> {
vec![
Self::ActorMayNotRequest {
action: RecoveryActionKind::RecoverHomeZ,
},
Self::PrintRunning {
state: PrinterState::Printing,
},
Self::PrinterUnreachable,
Self::OutOfBounds {
field: RecoveryField::Mm,
requested: 80.0,
allowed: Range::new(0.0, 50.0),
},
Self::AssertionRequired {
field: RecoveryField::BedClearAsserted,
},
Self::RecoveryNotConfigured,
Self::PrinterCannot {
action: RecoveryActionKind::RecoverPark,
detail: "this printer cannot move its head to a place".to_owned(),
},
]
}
}
impl Sample for ZTrust {
fn sample_full() -> Self {
Self::TrustedSince(Timestamp::sample_full())
}
fn sample_minimal() -> Self {
Self::Untrusted("the server started, and has homed no Z since".to_owned())
}
}
impl Sample for RecoveryPosition {
fn sample_full() -> Self {
Self {
x: 100.0,
y: 100.0,
z: 12.0,
}
}
}
impl Sample for ToolTemperature {
fn sample_full() -> Self {
Self {
tool: 0,
actual_c: Some(180.0),
target_c: Some(180.0),
}
}
fn sample_minimal() -> Self {
Self {
tool: 0,
actual_c: None,
target_c: None,
}
}
}
impl Sample for BedTemperature {
fn sample_full() -> Self {
Self {
actual_c: Some(60.0),
target_c: Some(0.0),
}
}
fn sample_minimal() -> Self {
Self {
actual_c: None,
target_c: None,
}
}
}
impl Sample for RecoveryTemperatures {
fn sample_full() -> Self {
Self {
tools: vec![ToolTemperature::sample_full()],
bed: Some(BedTemperature::sample_full()),
}
}
fn sample_minimal() -> Self {
Self {
tools: Vec::new(),
bed: None,
}
}
}
impl Sample for LastPrint {
fn sample_full() -> Self {
Self {
print_id: PrintId::sample_full(),
tallest_mm: 6.0,
footprint: Footprint::sample_full(),
}
}
}
impl Sample for PausedPrint {
fn sample_full() -> Self {
Self {
print_id: PrintId::sample_full(),
resumable: false,
}
}
}
impl Sample for ZHome {
fn sample_full() -> Self {
Self {
x: 125.0,
y: 105.0,
sweeps_bed: true,
}
}
}
impl Sample for ActionAllowance {
fn sample_full() -> Self {
Self {
action: RecoveryActionKind::RecoverPark,
refusal: Some(RecoveryRejection::ZUntrusted),
}
}
fn sample_minimal() -> Self {
Self {
action: RecoveryActionKind::RecoverLift,
refusal: None,
}
}
}
impl Sample for RecoveryStatus {
fn sample_full() -> Self {
Self {
state: PrinterState::Paused,
z_trust: ZTrust::sample_full(),
position: Some(RecoveryPosition::sample_full()),
temperatures: RecoveryTemperatures::sample_full(),
last_print: Some(LastPrint::sample_full()),
paused_print: Some(PausedPrint::sample_full()),
z_home: Some(ZHome::sample_full()),
actions: vec![
ActionAllowance::sample_minimal(),
ActionAllowance::sample_full(),
],
}
}
fn sample_minimal() -> Self {
Self {
state: PrinterState::Operational,
z_trust: ZTrust::sample_minimal(),
position: None,
temperatures: RecoveryTemperatures::sample_minimal(),
last_print: None,
paused_print: None,
z_home: None,
actions: Vec::new(),
}
}
}
impl Sample for RecoveryDecision {
fn sample_full() -> Self {
Self::Rejected(RecoveryRejection::sample_full())
}
fn sample_alternates() -> Vec<Self> {
vec![
Self::Executed(ExecutionOutcome::Succeeded),
Self::Executed(ExecutionOutcome::Failed {
reason: "the printer refused the request with 409: Printer is busy".to_owned(),
}),
]
}
}