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