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