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