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