Skip to main content

printobserver_printer_api/
snapshot.rs

1//! Normalized observations of a printer and of the job it is running.
2//!
3//! These are what [`PrinterPort::snapshot`](crate::PrinterPort::snapshot) and
4//! [`PrinterPort::job`](crate::PrinterPort::job) answer, declared beside the
5//! port whose methods carry them. Every numeric field a printer can report
6//! implausibly is typed [`Reported<f64>`] and read against the plausibility
7//! range [`ranges`](crate::ranges) declares for it: a flag that disagrees with
8//! the value under that range is refused on parse, so a snapshot never carries
9//! a reading whose flag was written by something other than its range.
10
11use printobserver_types::contract::Sample;
12use printobserver_types::reported::deserialize_ranged;
13use printobserver_types::schemars::JsonSchema;
14use printobserver_types::serde::{Deserialize, Deserializer, Serialize};
15use printobserver_types::{Reported, Timestamp};
16
17use crate::file::ToolFilament;
18use crate::state::PrinterState;
19
20use crate::ranges::{
21    COMPLETION_RANGE, FAN_PERCENT_RANGE, FEEDRATE_FACTOR_RANGE, FLOWRATE_FACTOR_RANGE,
22    HEATER_ACTUAL_C_RANGE, HEATER_OFFSET_C_RANGE, HEATER_TARGET_C_RANGE,
23};
24
25/// One heater, as a source reported it.
26///
27/// Every field is optional, because a source that reports no heater at all
28/// reports none of these; each is a plausibility-ranged reported value in
29/// degrees Celsius.
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
31#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
32#[schemars(crate = "printobserver_types::schemars")]
33pub struct HeaterSnapshot {
34    /// The temperature the heater is at.
35    #[serde(
36        default,
37        skip_serializing_if = "Option::is_none",
38        deserialize_with = "de_heater_actual_c"
39    )]
40    pub actual_c: Option<Reported<f64>>,
41    /// The temperature the heater is driving towards.
42    #[serde(
43        default,
44        skip_serializing_if = "Option::is_none",
45        deserialize_with = "de_heater_target_c"
46    )]
47    pub target_c: Option<Reported<f64>>,
48    /// The offset applied to this heater's target.
49    #[serde(
50        default,
51        skip_serializing_if = "Option::is_none",
52        deserialize_with = "de_heater_offset_c"
53    )]
54    pub offset_c: Option<Reported<f64>>,
55}
56
57/// A printer, as a source reported it at one instant.
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
59#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
60#[schemars(crate = "printobserver_types::schemars")]
61pub struct PrinterSnapshot {
62    /// The state the printer is in.
63    pub connection: PrinterState,
64    /// The tool heaters, indexed by tool number.
65    pub tools: Vec<HeaterSnapshot>,
66    /// The bed heater, when the printer reports one.
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub bed: Option<HeaterSnapshot>,
69    /// The chamber heater, when the printer reports one.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub chamber: Option<HeaterSnapshot>,
72    /// The feedrate multiplier, where one means one hundred percent.
73    #[serde(
74        default,
75        skip_serializing_if = "Option::is_none",
76        deserialize_with = "de_feedrate_factor"
77    )]
78    pub feedrate_factor: Option<Reported<f64>>,
79    /// The flowrate multiplier, where one means one hundred percent.
80    #[serde(
81        default,
82        skip_serializing_if = "Option::is_none",
83        deserialize_with = "de_flowrate_factor"
84    )]
85    pub flowrate_factor: Option<Reported<f64>>,
86    /// The part-cooling fan, in percent.
87    #[serde(
88        default,
89        skip_serializing_if = "Option::is_none",
90        deserialize_with = "de_fan_percent"
91    )]
92    pub fan_percent: Option<Reported<f64>>,
93    /// The instant this observation was taken.
94    pub observed_at: Timestamp,
95}
96
97/// Whose error a job's error is.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
99#[serde(
100    crate = "printobserver_types::serde",
101    rename_all = "snake_case",
102    deny_unknown_fields
103)]
104#[schemars(crate = "printobserver_types::schemars")]
105pub enum ErrorSource {
106    /// The printer's own message: its firmware stopped the job.
107    Printer,
108    /// The host's: it lost the line to the printer, or failed in itself.
109    Host,
110}
111
112impl Sample for ErrorSource {
113    fn sample_full() -> Self {
114        Self::Printer
115    }
116
117    fn sample_alternates() -> Vec<Self> {
118        vec![Self::Host]
119    }
120}
121
122/// A job's error, and whose it is.
123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
124#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
125#[schemars(crate = "printobserver_types::schemars")]
126pub struct JobError {
127    /// The error, as the source reported it.
128    pub text: String,
129    /// Whose it is.
130    pub source: ErrorSource,
131}
132
133impl Sample for JobError {
134    fn sample_full() -> Self {
135        Self {
136            text: "Thermal Runaway, system stopped!".to_owned(),
137            source: ErrorSource::Printer,
138        }
139    }
140
141    fn sample_alternates() -> Vec<Self> {
142        vec![Self {
143            text: "SerialTimeoutException: ".to_owned(),
144            source: ErrorSource::Host,
145        }]
146    }
147}
148
149/// The job a printer reports it is running.
150///
151/// Every field but `state` is optional: an absent one means the source did not
152/// report it.
153#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
154#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
155#[schemars(crate = "printobserver_types::schemars")]
156pub struct JobSnapshot {
157    /// The name of the file being printed, as the source reported it.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub file_name: Option<String>,
160    /// Where the file lives, in the source's own vocabulary.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub file_origin: Option<String>,
163    /// The file's size in bytes.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub size_bytes: Option<i64>,
166    /// The whole print's estimated duration, in whole seconds.
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub estimated_print_time_s: Option<i64>,
169    /// How far through the print is, as a fraction from zero to one.
170    ///
171    /// Normalized to a fraction here regardless of how the source expresses it.
172    #[serde(
173        default,
174        skip_serializing_if = "Option::is_none",
175        deserialize_with = "de_completion"
176    )]
177    pub completion: Option<Reported<f64>>,
178    /// How long the print has been running, in whole seconds.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub print_time_s: Option<i64>,
181    /// How long the print has left, in whole seconds.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub print_time_left_s: Option<i64>,
184    /// The state the source reports the job to be in.
185    pub state: PrinterState,
186    /// The error the source reports, when it reports one, and whose it is.
187    #[serde(default, skip_serializing_if = "Option::is_none")]
188    pub error: Option<JobError>,
189    /// How far into the file the printer has read, in bytes, when the source
190    /// reported it.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub file_position_bytes: Option<i64>,
193    /// The filament the source's analysis of the file says each tool uses;
194    /// empty when the source reported none.
195    #[serde(default, skip_serializing_if = "Vec::is_empty")]
196    pub filament: Vec<ToolFilament>,
197}
198
199/// Read `PrinterSnapshot::feedrate_factor` against its declared range.
200fn de_feedrate_factor<'de, D: Deserializer<'de>>(
201    deserializer: D,
202) -> Result<Option<Reported<f64>>, D::Error> {
203    deserialize_ranged(deserializer, "feedrate_factor", FEEDRATE_FACTOR_RANGE)
204}
205
206/// Read `PrinterSnapshot::flowrate_factor` against its declared range.
207fn de_flowrate_factor<'de, D: Deserializer<'de>>(
208    deserializer: D,
209) -> Result<Option<Reported<f64>>, D::Error> {
210    deserialize_ranged(deserializer, "flowrate_factor", FLOWRATE_FACTOR_RANGE)
211}
212
213/// Read `PrinterSnapshot::fan_percent` against its declared range.
214fn de_fan_percent<'de, D: Deserializer<'de>>(
215    deserializer: D,
216) -> Result<Option<Reported<f64>>, D::Error> {
217    deserialize_ranged(deserializer, "fan_percent", FAN_PERCENT_RANGE)
218}
219
220/// Read `JobSnapshot::completion` against its declared range.
221fn de_completion<'de, D: Deserializer<'de>>(
222    deserializer: D,
223) -> Result<Option<Reported<f64>>, D::Error> {
224    deserialize_ranged(deserializer, "completion", COMPLETION_RANGE)
225}
226
227/// Read `HeaterSnapshot::actual_c` against its declared range.
228fn de_heater_actual_c<'de, D: Deserializer<'de>>(
229    deserializer: D,
230) -> Result<Option<Reported<f64>>, D::Error> {
231    deserialize_ranged(deserializer, "actual_c", HEATER_ACTUAL_C_RANGE)
232}
233
234/// Read `HeaterSnapshot::target_c` against its declared range.
235fn de_heater_target_c<'de, D: Deserializer<'de>>(
236    deserializer: D,
237) -> Result<Option<Reported<f64>>, D::Error> {
238    deserialize_ranged(deserializer, "target_c", HEATER_TARGET_C_RANGE)
239}
240
241/// Read `HeaterSnapshot::offset_c` against its declared range.
242fn de_heater_offset_c<'de, D: Deserializer<'de>>(
243    deserializer: D,
244) -> Result<Option<Reported<f64>>, D::Error> {
245    deserialize_ranged(deserializer, "offset_c", HEATER_OFFSET_C_RANGE)
246}
247
248impl Sample for HeaterSnapshot {
249    fn sample_full() -> Self {
250        Self {
251            actual_c: Some(Reported::new(214.5, HEATER_ACTUAL_C_RANGE)),
252            target_c: Some(Reported::new(215.0, HEATER_TARGET_C_RANGE)),
253            offset_c: Some(Reported::new(0.0, HEATER_OFFSET_C_RANGE)),
254        }
255    }
256
257    fn sample_minimal() -> Self {
258        Self {
259            actual_c: None,
260            target_c: None,
261            offset_c: None,
262        }
263    }
264}
265
266impl Sample for PrinterSnapshot {
267    fn sample_full() -> Self {
268        Self {
269            connection: PrinterState::Printing,
270            tools: vec![HeaterSnapshot::sample_full()],
271            bed: Some(HeaterSnapshot::sample_full()),
272            chamber: Some(HeaterSnapshot::sample_full()),
273            feedrate_factor: Some(Reported::new(1.0, FEEDRATE_FACTOR_RANGE)),
274            flowrate_factor: Some(Reported::new(1.0, FLOWRATE_FACTOR_RANGE)),
275            fan_percent: Some(Reported::new(100.0, FAN_PERCENT_RANGE)),
276            observed_at: Timestamp::sample_full(),
277        }
278    }
279
280    fn sample_minimal() -> Self {
281        Self {
282            connection: PrinterState::Printing,
283            tools: vec![],
284            bed: None,
285            chamber: None,
286            feedrate_factor: None,
287            flowrate_factor: None,
288            fan_percent: None,
289            observed_at: Timestamp::sample_full(),
290        }
291    }
292}
293
294impl Sample for JobSnapshot {
295    fn sample_full() -> Self {
296        Self {
297            file_name: Some("benchy.gcode".to_owned()),
298            file_origin: Some("local".to_owned()),
299            size_bytes: Some(4_194_304),
300            estimated_print_time_s: Some(7200),
301            completion: Some(Reported::new(0.42, COMPLETION_RANGE)),
302            print_time_s: Some(3024),
303            print_time_left_s: Some(4176),
304            state: PrinterState::Printing,
305            error: Some(JobError::sample_full()),
306            file_position_bytes: Some(1_761_607),
307            filament: vec![ToolFilament::sample_full()],
308        }
309    }
310
311    fn sample_minimal() -> Self {
312        Self {
313            file_name: None,
314            file_origin: None,
315            size_bytes: None,
316            estimated_print_time_s: None,
317            completion: None,
318            print_time_s: None,
319            print_time_left_s: None,
320            state: PrinterState::Printing,
321            error: None,
322            file_position_bytes: None,
323            filament: Vec::new(),
324        }
325    }
326}