Skip to main content

printobserver_printer_api/
adjustable.rs

1//! The closed set of things an adjustment may change.
2//!
3//! This is the printer domain's vocabulary: each member names what one of
4//! the port's setters — [`set_feedrate_factor`] and the four beside it —
5//! changes on the machine, and it is what a manifest, an envelope and a
6//! bounded intervention name a bound by. It is declared beside the port whose
7//! methods it is the vocabulary of, so that a printer that gains an adjustable
8//! edits this crate and the adapters behind it, and nothing central.
9//!
10//! [`set_feedrate_factor`]: crate::PrinterPort::set_feedrate_factor
11
12use core::fmt;
13use core::str::FromStr;
14use std::borrow::Cow;
15
16use printobserver_types::contract::Sample;
17use printobserver_types::schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
18use printobserver_types::serde::{
19    Deserialize, Deserializer, Serialize, Serializer, de::Error as _,
20};
21
22/// The prefix the tool-target adjustable spells its tool number after.
23const TOOL_TARGET: &str = "tool_target";
24
25/// One thing an adjustment may change.
26///
27/// Serialized as a string rather than an object, because this is the key type
28/// of the manifest's, the envelope's and the effective bounds' maps, and a JSON
29/// object key is a string. The spellings are `feedrate`, `flowrate`,
30/// `bed_target`, `fan`, and `tool_target:<number>`.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
32pub enum Adjustable {
33    /// The feedrate factor.
34    Feedrate,
35    /// The flowrate factor.
36    Flowrate,
37    /// One tool's target temperature, carrying that tool's number.
38    ToolTarget {
39        /// The tool number, in the printer's own numbering.
40        tool: i64,
41    },
42    /// The bed's target temperature.
43    BedTarget,
44    /// The part-cooling fan.
45    Fan,
46}
47
48/// Why a string is no adjustable.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct AdjustableError {
51    /// What is wrong with the string.
52    detail: String,
53}
54
55impl AdjustableError {
56    /// What is wrong with the string.
57    #[must_use]
58    pub fn detail(&self) -> &str {
59        &self.detail
60    }
61}
62
63impl fmt::Display for AdjustableError {
64    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65        write!(formatter, "not an adjustable: {}", self.detail)
66    }
67}
68
69impl core::error::Error for AdjustableError {}
70
71impl fmt::Display for Adjustable {
72    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
73        match self {
74            Self::Feedrate => formatter.write_str("feedrate"),
75            Self::Flowrate => formatter.write_str("flowrate"),
76            Self::ToolTarget { tool } => write!(formatter, "{TOOL_TARGET}:{tool}"),
77            Self::BedTarget => formatter.write_str("bed_target"),
78            Self::Fan => formatter.write_str("fan"),
79        }
80    }
81}
82
83impl FromStr for Adjustable {
84    type Err = AdjustableError;
85
86    fn from_str(text: &str) -> Result<Self, Self::Err> {
87        match text {
88            "feedrate" => return Ok(Self::Feedrate),
89            "flowrate" => return Ok(Self::Flowrate),
90            "bed_target" => return Ok(Self::BedTarget),
91            "fan" => return Ok(Self::Fan),
92            _ => {}
93        }
94        let Some(number) = text.strip_prefix(concat!("tool_target", ":")) else {
95            return Err(AdjustableError {
96                detail: format!("{text:?} names no adjustable"),
97            });
98        };
99        number
100            .parse()
101            .map(|tool| Self::ToolTarget { tool })
102            .map_err(|error| AdjustableError {
103                detail: format!("{text:?} carries no tool number: {error}"),
104            })
105    }
106}
107
108impl Serialize for Adjustable {
109    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
110        serializer.collect_str(self)
111    }
112}
113
114impl<'de> Deserialize<'de> for Adjustable {
115    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
116        let text = String::deserialize(deserializer)?;
117        text.parse().map_err(D::Error::custom)
118    }
119}
120
121impl JsonSchema for Adjustable {
122    fn schema_name() -> Cow<'static, str> {
123        Cow::Borrowed("Adjustable")
124    }
125
126    fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
127        json_schema!({
128            "type": "string",
129            "title": "Adjustable",
130            "description": "One thing an adjustment may change.",
131            "pattern": "^(feedrate|flowrate|bed_target|fan|tool_target:-?[0-9]+)$"
132        })
133    }
134}
135
136impl Sample for Adjustable {
137    fn sample_full() -> Self {
138        Self::ToolTarget { tool: 0 }
139    }
140}