Skip to main content

printobserver_printer_api/
lib.rs

1//! `printobserver-printer-api`.
2//!
3//! Owns: the port the physical printer speaks through — the trait for reading
4//! printer and job state and for asking the machine to do one of the bounded
5//! things the action vocabulary names, plus that port's own error type — and
6//! the printer domain's vocabulary: the state a printer reports ([`state`]),
7//! the closed set of things an adjustment may change ([`adjustable`]), the
8//! snapshots those reads answer ([`snapshot`]), what the printer knows of the
9//! files it holds and the filament they use ([`file`]) and the plausibility ranges
10//! their reported numbers are read against ([`ranges`]). A change to what a
11//! printer reports edits this crate and the adapters behind it, and nothing
12//! central.
13//!
14//! May depend on: `printobserver-types` only. A port that named an
15//! implementation would stop being a port.
16//!
17//! # What this port does not expose
18//!
19//! There is no method that accepts a command string, and that absence is the
20//! contract rather than an omission: no method here admits a byte sequence at
21//! all, and the only string anywhere in the closure reachable from a method's
22//! parameters is the one [`FileName`] wraps, which only
23//! [`PrinterPort::start`] and the two reads of one file —
24//! [`PrinterPort::file_facts`] and [`PrinterPort::extruded_to`] — take. Every value a method takes is already
25//! bounded by the time it arrives: policy has ruled on it before it gets here.
26//!
27//! # Why the methods answer a boxed future
28//!
29//! Every method is asynchronous, and the trait is dyn-compatible and shareable
30//! across threads, because the supervision core holds every port behind
31//! `Arc<dyn Port>`. An `async fn` in a trait is not dyn-compatible, so each
32//! method answers a [`BoxFuture`] instead: the same asynchrony, in the one
33//! shape a trait object can carry.
34
35pub mod adjustable;
36pub mod file;
37pub mod ranges;
38pub mod snapshot;
39pub mod state;
40
41use core::future::Future;
42use core::pin::Pin;
43
44use printobserver_types::FileName;
45
46pub use adjustable::{Adjustable, AdjustableError};
47pub use file::{FileFacts, FilePrint, ToolFilament};
48pub use ranges::{
49    COMPLETION_RANGE, FAN_PERCENT_RANGE, FEEDRATE_FACTOR_RANGE, FLOWRATE_FACTOR_RANGE,
50    HEATER_ACTUAL_C_RANGE, HEATER_OFFSET_C_RANGE, HEATER_TARGET_C_RANGE, RANGED_FIELDS,
51    RangedField,
52};
53pub use snapshot::{HeaterSnapshot, JobSnapshot, PrinterSnapshot};
54pub use state::PrinterState;
55
56/// A future this port's methods answer with, in the one shape a trait object
57/// can carry.
58pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
59
60/// Why the printer did not do what it was asked.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum PrinterError {
63    /// The printer could not be reached at all.
64    Unreachable {
65        /// What went wrong reaching it.
66        detail: String,
67    },
68    /// The printer refused the credentials.
69    Unauthorized {
70        /// What the printer said about them.
71        detail: String,
72    },
73    /// The printer refused the request, in its own words.
74    Refused {
75        /// The status the source answered with.
76        status: u16,
77        /// What the source said.
78        detail: String,
79    },
80    /// The printer is not in a state this request is valid from.
81    StateConflict {
82        /// What the source said about the state.
83        detail: String,
84    },
85    /// This printer cannot express that adjustable at all.
86    Unsupported {
87        /// The adjustable this printer does not have.
88        adjustable: Adjustable,
89    },
90    /// The printer answered something this port could not read.
91    Malformed {
92        /// What could not be read.
93        detail: String,
94    },
95}
96
97impl core::fmt::Display for PrinterError {
98    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
99        match self {
100            Self::Unreachable { detail } => {
101                write!(formatter, "the printer is unreachable: {detail}")
102            }
103            Self::Unauthorized { detail } => {
104                write!(formatter, "the printer refused the credentials: {detail}")
105            }
106            Self::Refused { status, detail } => {
107                write!(
108                    formatter,
109                    "the printer refused the request with {status}: {detail}"
110                )
111            }
112            Self::StateConflict { detail } => {
113                write!(
114                    formatter,
115                    "the printer is not in a state this is valid from: {detail}"
116                )
117            }
118            Self::Unsupported { adjustable } => {
119                write!(formatter, "this printer has no {adjustable}")
120            }
121            Self::Malformed { detail } => {
122                write!(
123                    formatter,
124                    "the printer answered something unreadable: {detail}"
125                )
126            }
127        }
128    }
129}
130
131impl core::error::Error for PrinterError {}
132
133/// The port the physical printer speaks through.
134///
135/// Every method is asynchronous, the trait is dyn-compatible, and it is
136/// shareable across threads, because the supervision core holds it behind
137/// `Arc<dyn PrinterPort>`.
138pub trait PrinterPort: Send + Sync {
139    /// Read the printer's current state.
140    fn snapshot(&self) -> BoxFuture<'_, Result<PrinterSnapshot, PrinterError>>;
141
142    /// Read the job the printer reports it is running.
143    fn job(&self) -> BoxFuture<'_, Result<JobSnapshot, PrinterError>>;
144
145    /// Start a print of a named file.
146    fn start(&self, file_name: FileName) -> BoxFuture<'_, Result<(), PrinterError>>;
147
148    /// Pause the print.
149    fn pause(&self) -> BoxFuture<'_, Result<(), PrinterError>>;
150
151    /// Resume the print.
152    fn resume(&self) -> BoxFuture<'_, Result<(), PrinterError>>;
153
154    /// Cancel the print.
155    fn cancel(&self) -> BoxFuture<'_, Result<(), PrinterError>>;
156
157    /// Set the feedrate multiplier, where one means one hundred percent.
158    fn set_feedrate_factor(&self, factor: f64) -> BoxFuture<'_, Result<(), PrinterError>>;
159
160    /// Set the flowrate multiplier, where one means one hundred percent.
161    fn set_flowrate_factor(&self, factor: f64) -> BoxFuture<'_, Result<(), PrinterError>>;
162
163    /// Set one tool's target temperature, in degrees Celsius.
164    fn set_tool_target_c(
165        &self,
166        tool: i64,
167        target_c: f64,
168    ) -> BoxFuture<'_, Result<(), PrinterError>>;
169
170    /// Set the bed's target temperature, in degrees Celsius.
171    fn set_bed_target_c(&self, target_c: f64) -> BoxFuture<'_, Result<(), PrinterError>>;
172
173    /// Set the part-cooling fan, in percent.
174    fn set_fan_percent(&self, percent: f64) -> BoxFuture<'_, Result<(), PrinterError>>;
175
176    /// Read what the printer knows of one file it holds.
177    ///
178    /// A printer that cannot answer is refused with status 501, which is what
179    /// an implementation that does not override this answers.
180    fn file_facts(&self, file_name: FileName) -> BoxFuture<'_, Result<FileFacts, PrinterError>> {
181        let _ = file_name;
182        Box::pin(async { Err(not_supported("file_facts")) })
183    }
184
185    /// Read every file the printer holds that carries a print tally.
186    ///
187    /// A printer that cannot answer is refused with status 501, which is what
188    /// an implementation that does not override this answers.
189    fn printed_files(&self) -> BoxFuture<'_, Result<Vec<FileFacts>, PrinterError>> {
190        Box::pin(async { Err(not_supported("printed_files")) })
191    }
192
193    /// Read the filament each tool is fed by one file's own moves, from its
194    /// start up to a byte position in it.
195    ///
196    /// A printer that cannot answer is refused with status 501, which is what
197    /// an implementation that does not override this answers.
198    fn extruded_to(
199        &self,
200        file_name: FileName,
201        position_bytes: i64,
202    ) -> BoxFuture<'_, Result<Vec<ToolFilament>, PrinterError>> {
203        let _ = (file_name, position_bytes);
204        Box::pin(async { Err(not_supported("extruded_to")) })
205    }
206}
207
208/// What a printer that does not implement one of the file reads answers.
209fn not_supported(method: &str) -> PrinterError {
210    PrinterError::Refused {
211        status: 501,
212        detail: format!("{method} is not supported by this printer"),
213    }
214}