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