Skip to main content

printobserver_core/records/
charge.rs

1//! What a print took from a spool, and the durable identity of each debit.
2//!
3//! A charge is keyed rather than counted: every debit carries the
4//! [`ChargeKey`] naming exactly which stretch of which print on which tool it
5//! is for, so a replay of the same observation finds the key already charged
6//! and debits nothing twice. Filament a tool fed after a filament change nobody
7//! confirmed is held as a [`PendingCharge`] until somebody says which spool fed
8//! it, so a spool that really was fed is never left undebited.
9
10use printobserver_types::schemars::JsonSchema;
11use printobserver_types::serde::{Deserialize, Serialize};
12use printobserver_types::{PrintId, Timestamp};
13
14use super::ids::SpoolId;
15
16/// How a print ended.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
18#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
19#[schemars(crate = "printobserver_types::schemars")]
20pub enum PrintOutcome {
21    /// It ran to its end.
22    Completed,
23    /// Somebody cancelled it.
24    Cancelled,
25    /// It stopped on an error.
26    Failed,
27    /// It stopped with no cancel, no error the printer reported and no
28    /// finish. Charged as a failed print is: what the file's moves extruded up
29    /// to the last file position seen.
30    Interrupted,
31}
32
33/// How the length a charge debits was worked out.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
35#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
36#[schemars(crate = "printobserver_types::schemars")]
37pub enum ChargeMethod {
38    /// A completed print: the length the file's analysis gives.
39    SlicerEstimate,
40    /// The extrusion the file's own moves add up to, up to a position in it.
41    GcodeExtrusion,
42    /// The analysed length scaled by how far into the file the print got; the
43    /// fallback used only when the file itself could not be read.
44    FileFraction,
45    /// A completed print this system never saw: the file's analysed length.
46    UnobservedEstimate,
47}
48
49/// The durable identity of one debit, so that a replay can never debit twice.
50#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
51#[serde(
52    crate = "printobserver_types::serde",
53    tag = "key",
54    rename_all = "snake_case",
55    deny_unknown_fields
56)]
57#[schemars(crate = "printobserver_types::schemars")]
58pub enum ChargeKey {
59    /// One segment of a print this system watched, on one tool.
60    Print {
61        /// The print.
62        print_id: PrintId,
63        /// The tool, in the printer's own numbering.
64        tool: i64,
65        /// Which segment: zero from the print's start, and one more each time
66        /// a mid-print swap or a filament-change signal closes the current one.
67        segment: u32,
68    },
69    /// One print this system never saw, on one tool.
70    Unobserved {
71        /// Where the file lives, in the printer's own vocabulary.
72        origin: String,
73        /// The file that was printed.
74        file_name: String,
75        /// The file's tally generation, which advances each time the printer's
76        /// tally for the file is reset.
77        generation: u32,
78        /// The print's ordinal in the file's tally — completed and failed
79        /// prints counted up to and including this one — within that
80        /// generation.
81        print_number: i64,
82        /// The tool, in the printer's own numbering.
83        tool: i64,
84    },
85}
86
87impl ChargeKey {
88    /// The one spelling this key is stored under.
89    ///
90    /// `print:<print_id>:<tool>:<segment>` for a watched print and
91    /// `unobserved:<origin>:<generation>:<print_number>:<tool>:<file_name>`
92    /// for one this system never saw — the file name last, because it is the
93    /// one part that may itself carry a colon.
94    #[must_use]
95    pub fn canonical(&self) -> String {
96        match self {
97            Self::Print {
98                print_id,
99                tool,
100                segment,
101            } => format!("print:{print_id}:{tool}:{segment}"),
102            Self::Unobserved {
103                origin,
104                file_name,
105                generation,
106                print_number,
107                tool,
108            } => format!("unobserved:{origin}:{generation}:{print_number}:{tool}:{file_name}"),
109        }
110    }
111}
112
113/// One segment of a print this system watched, on one tool: the key of a
114/// [`ChargeKey::Print`] debit, and the only key filament held pending can be
115/// under.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
117#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
118#[schemars(crate = "printobserver_types::schemars")]
119pub struct PrintSegmentKey {
120    /// The print.
121    pub print_id: PrintId,
122    /// The tool, in the printer's own numbering.
123    pub tool: i64,
124    /// Which segment, numbered as [`ChargeKey::Print`] numbers it.
125    pub segment: u32,
126}
127
128impl PrintSegmentKey {
129    /// The charge key this segment is debited under.
130    #[must_use]
131    pub const fn charge_key(&self) -> ChargeKey {
132        ChargeKey::Print {
133            print_id: self.print_id,
134            tool: self.tool,
135            segment: self.segment,
136        }
137    }
138}
139
140impl ChargeKey {
141    /// The tool the debit is for, as every key names it.
142    #[must_use]
143    pub const fn tool(&self) -> i64 {
144        match self {
145            Self::Print { tool, .. } | Self::Unobserved { tool, .. } => *tool,
146        }
147    }
148
149    /// The watched print the debit is for, when the key names one.
150    #[must_use]
151    pub const fn watched_print(&self) -> Option<PrintId> {
152        match self {
153            Self::Print { print_id, .. } => Some(*print_id),
154            Self::Unobserved { .. } => None,
155        }
156    }
157
158    /// The print segment this key names, when it names one.
159    #[must_use]
160    pub const fn print_segment(&self) -> Option<PrintSegmentKey> {
161        match self {
162            Self::Print {
163                print_id,
164                tool,
165                segment,
166            } => Some(PrintSegmentKey {
167                print_id: *print_id,
168                tool: *tool,
169                segment: *segment,
170            }),
171            Self::Unobserved { .. } => None,
172        }
173    }
174}
175
176/// What a charge took from a spool, and the whole calculation behind it.
177///
178/// Present or absent as one: a debit names its spool exactly when it carries
179/// the grams, the figures they were worked out with, and the spool's figure
180/// either side of them.
181#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
182#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
183#[schemars(crate = "printobserver_types::schemars")]
184pub struct ChargedFilament {
185    /// The spool charged.
186    pub spool_id: SpoolId,
187    /// What the length weighs, in grams; what is subtracted from the spool.
188    pub grams: f64,
189    /// The diameter the grams were worked out with, in millimetres.
190    pub diameter_mm: f64,
191    /// The density the grams were worked out with, in grams per cubic
192    /// centimetre.
193    pub density_g_cm3: f64,
194    /// The spool's figure before the charge, in grams.
195    pub remaining_before_g: f64,
196    /// The spool's figure after it, in grams.
197    pub remaining_after_g: f64,
198}
199
200/// How far into its file a print had got, and when that was read.
201#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
202#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
203#[schemars(crate = "printobserver_types::schemars")]
204pub struct FilePosition {
205    /// The byte the printer had read the file up to.
206    pub bytes: i64,
207    /// The file's size in bytes, when it was known.
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub size_bytes: Option<i64>,
210    /// When the position was read.
211    pub observed_at: Timestamp,
212}
213
214/// Filament a tool fed after a filament change nobody has confirmed, held until
215/// somebody says which spool fed it.
216///
217/// A length rather than grams, because the grams follow the spool that takes
218/// it.
219#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
220#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
221#[schemars(crate = "printobserver_types::schemars")]
222pub struct PendingCharge {
223    /// The print segment the filament was fed in, which names the print and
224    /// the tool that fed it.
225    pub charge_key: PrintSegmentKey,
226    /// How much was fed, in millimetres.
227    pub length_mm: f64,
228    /// How that length was worked out.
229    pub method: ChargeMethod,
230    /// The file's analysed length for the tool, in millimetres, when it had one.
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub analysed_length_mm: Option<f64>,
233    /// How far into the file the segment ran, when that was read.
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub position: Option<FilePosition>,
236    /// Anything a reader needs to make sense of the figure.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub note: Option<String>,
239    /// When it was held.
240    pub pended_at: Timestamp,
241}
242
243impl PendingCharge {
244    /// The print the filament was fed in.
245    #[must_use]
246    pub const fn print_id(&self) -> PrintId {
247        self.charge_key.print_id
248    }
249
250    /// The tool that fed it.
251    #[must_use]
252    pub const fn tool(&self) -> i64 {
253        self.charge_key.tool
254    }
255}
256
257/// One pending charge a spool command took.
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
259#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
260#[schemars(crate = "printobserver_types::schemars")]
261pub struct PendingTaken {
262    /// The key it is charged under.
263    pub charge_key: ChargeKey,
264    /// The print it was fed in.
265    pub print_id: PrintId,
266}