printobserver_core/config.rs
1//! What a running supervisor is configured with.
2
3use std::collections::BTreeMap;
4use std::time::Duration;
5
6use crate::records::{MaterialName, SafetyEnvelope, SheetId};
7use printobserver_types::PrintId;
8use printobserver_types::serde::{Deserialize, Serialize};
9use printobserver_vision_api::WebAddress;
10
11/// The placeholder [`CoreConfig::context_command`] substitutes the print for.
12pub const PRINT_ID_PLACEHOLDER: &str = "{print_id}";
13
14/// How often the expiry driver looks for a bounded intervention that is due.
15pub const DEFAULT_EXPIRY_POLL: Duration = Duration::from_millis(250);
16
17/// How many of a print's own events a supervision turn is given.
18pub const DEFAULT_RECENT_EVENTS: u32 = 20;
19
20/// How long after the agent's last adjustment to a print the detector paused
21/// that print is resumed, when its turn has not ended first.
22///
23/// Long enough for an agent to ask for the two or three changes it decided on
24/// one after the other, so that they reach the print together as it moves
25/// again; short enough that a paused hot end is not left sitting.
26pub const DEFAULT_DETECTOR_RESUME_GRACE: Duration = Duration::from_secs(20);
27
28/// How often every active print is observed when no detector has said
29/// anything about it.
30///
31/// A frozen progress, a heater that went cold mid-print, a fan cut at a bridge
32/// and an under-extruding wall all stay below what a failure detector alerts
33/// on, so a print whose only trigger was the detector would never be looked at
34/// for any of them. Two minutes is the rate the user chose: often enough to
35/// catch a stall before it has printed far into the air, and an eight-hour
36/// print is 240 turns.
37pub const DEFAULT_OBSERVATION_INTERVAL: Duration = Duration::from_secs(120);
38
39/// The longest one look may wait for something to happen, in seconds.
40///
41/// Below the two minutes a supervising agent's own shell gives one command, so
42/// that a look is never cut off by the tool that asked for it. A longer wait is
43/// refused rather than shortened.
44pub const MAX_LOOK_WAIT_S: u32 = 90;
45
46/// What a start does when the filament check finds a spool short, unverified,
47/// or a file with no analysis.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
49#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
50pub enum PreflightMode {
51 /// Refuse the start, unless the actor overrides the check.
52 #[default]
53 Refuse,
54 /// Let the start go ahead, and record that the check warned.
55 Warn,
56 /// Make no check at all.
57 Off,
58}
59
60/// How spools are checked before a print, and the margin asked for.
61#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
62#[serde(crate = "printobserver_types::serde", default, deny_unknown_fields)]
63pub struct SpoolPolicy {
64 /// What a start does when the check finds a problem.
65 pub preflight: PreflightMode,
66 /// The margin asked for beyond a print's requirement, as a percentage of
67 /// it.
68 pub buffer_percent: f64,
69 /// The least margin asked for, in grams, however small the print.
70 pub buffer_min_g: f64,
71 /// How long a start waits for `OctoPrint`'s analysis of a file that has
72 /// none yet, in whole seconds; zero waits not at all.
73 pub analysis_wait_s: u64,
74}
75
76impl Default for SpoolPolicy {
77 fn default() -> Self {
78 Self {
79 preflight: PreflightMode::Refuse,
80 buffer_percent: 10.0,
81 buffer_min_g: 5.0,
82 analysis_wait_s: 300,
83 }
84 }
85}
86
87/// The build sheets each material may be printed on when the configuration
88/// names no table of its own.
89///
90/// PLA on smooth PEI and PETG on textured PEI: PLA lifts off textured PEI's
91/// grain, and PETG can bond to smooth PEI hard enough to tear the sheet
92/// without glue.
93pub const DEFAULT_SHEETS: [(&str, &[&str]); 2] =
94 [("PLA", &["smooth-pei"]), ("PETG", &["textured-pei"])];
95
96/// Which build sheets each material may be printed on, keyed by material.
97///
98/// Materials and sheets are matched trimmed and without regard to case, as a
99/// spool's own material is written by whoever registered it. A table is
100/// never empty in either direction: every material lists at least one sheet
101/// and nothing is blank.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct SheetTable {
104 /// Each material, as written, and the sheets it may be printed on.
105 entries: BTreeMap<MaterialName, Vec<SheetId>>,
106}
107
108impl SheetTable {
109 /// A table of these entries.
110 ///
111 /// # Errors
112 ///
113 /// Returns why the entries are no table: a blank material or sheet, a
114 /// material listing no sheet, or two materials that differ only in case
115 /// or surrounding space.
116 pub fn new(entries: BTreeMap<String, Vec<String>>) -> Result<Self, String> {
117 let mut table: BTreeMap<MaterialName, Vec<SheetId>> = BTreeMap::new();
118 for (material, sheets) in entries {
119 let material = MaterialName::try_from(material)?;
120 if table.keys().any(|listed| listed.same(&material)) {
121 return Err(format!(
122 "{material} is listed twice, once differing only in case or space"
123 ));
124 }
125 if sheets.is_empty() {
126 return Err(format!(
127 "{material} lists no sheet; leave a material out rather than list it on none"
128 ));
129 }
130 let sheets = sheets
131 .into_iter()
132 .map(SheetId::try_from)
133 .collect::<Result<Vec<_>, _>>()
134 .map_err(|why| format!("{material} lists a sheet that is blank: {why}"))?;
135 table.insert(material, sheets);
136 }
137 Ok(Self { entries: table })
138 }
139
140 /// The sheets the table allows a material on, when it lists the material.
141 #[must_use]
142 pub fn allowed_for(&self, material: &MaterialName) -> Option<&[SheetId]> {
143 self.entries
144 .iter()
145 .find(|(listed, _)| listed.same(material))
146 .map(|(_, sheets)| sheets.as_slice())
147 }
148
149 /// Whether any entry lists a sheet.
150 #[must_use]
151 pub fn lists(&self, sheet: &SheetId) -> bool {
152 self.entries
153 .values()
154 .flatten()
155 .any(|listed| listed.same(sheet))
156 }
157
158 /// Every sheet some entry lists, once each, in order.
159 #[must_use]
160 pub fn sheets(&self) -> Vec<SheetId> {
161 let mut known: Vec<SheetId> = Vec::new();
162 for sheet in self.entries.values().flatten() {
163 if !known.iter().any(|listed| listed.same(sheet)) {
164 known.push(sheet.clone());
165 }
166 }
167 known.sort();
168 known
169 }
170}
171
172impl Default for SheetTable {
173 fn default() -> Self {
174 Self::new(
175 DEFAULT_SHEETS
176 .iter()
177 .map(|(material, sheets)| {
178 (
179 (*material).to_owned(),
180 sheets.iter().map(|sheet| (*sheet).to_owned()).collect(),
181 )
182 })
183 .collect(),
184 )
185 .unwrap_or_else(|why| unreachable!("the default sheet table is a table: {why}"))
186 }
187}
188
189/// The server configuration supervision reads.
190#[derive(Debug, Clone, PartialEq)]
191pub struct CoreConfig {
192 /// The operator's safety envelope: what any actor may ask for at all.
193 pub envelope: SafetyEnvelope,
194 /// The command a supervision turn runs to read the print's context.
195 ///
196 /// [`PRINT_ID_PLACEHOLDER`] in it is replaced with the print's own
197 /// identifier, so that a turn reads the context of the print it is about.
198 pub context_command: String,
199 /// How many of the print's own events a turn is given, newest first.
200 pub recent_events: u32,
201 /// How often the expiry driver looks for an intervention that is due.
202 pub expiry_poll: Duration,
203 /// Where a fresh frame of the print is fetched from, when a camera is
204 /// configured.
205 pub camera_snapshot_url: Option<WebAddress>,
206 /// How often, and how far apart, a fetch the camera answered with a
207 /// server error is made again.
208 pub camera_retry: crate::look::CameraRetry,
209 /// How long after the agent's last adjustment a print the detector paused
210 /// is resumed.
211 pub detector_resume_grace: Duration,
212 /// How often every active print is given a periodic observation.
213 pub observation_interval: Duration,
214 /// How spools are checked before a print, and the margin asked for.
215 pub spools: SpoolPolicy,
216 /// Which build sheets each material may be printed on.
217 pub sheets: SheetTable,
218 /// How often the printer watch reads the machine.
219 pub printer_poll: Duration,
220 /// How long after an `interrupted` or `failed` ending the printer acting
221 /// on its own is recorded.
222 pub unattended_window: Duration,
223 /// The printer's own facts a recovery is checked against; absent, every
224 /// recovery action is refused as not configured.
225 pub recovery: Option<crate::records::RecoveryConfig>,
226 /// Who may ask for which recovery action.
227 pub recovery_grants: crate::records::RecoveryGrants,
228}
229
230impl CoreConfig {
231 /// The configuration for one envelope, with this crate's own defaults.
232 #[must_use]
233 pub fn new(envelope: SafetyEnvelope, context_command: String) -> Self {
234 Self {
235 envelope,
236 context_command,
237 recent_events: DEFAULT_RECENT_EVENTS,
238 expiry_poll: DEFAULT_EXPIRY_POLL,
239 camera_snapshot_url: None,
240 camera_retry: crate::look::CameraRetry::default(),
241 detector_resume_grace: DEFAULT_DETECTOR_RESUME_GRACE,
242 observation_interval: DEFAULT_OBSERVATION_INTERVAL,
243 spools: SpoolPolicy::default(),
244 sheets: SheetTable::default(),
245 printer_poll: crate::watch::DEFAULT_PRINTER_POLL,
246 unattended_window: crate::watch::DEFAULT_UNATTENDED_WINDOW,
247 recovery: None,
248 recovery_grants: crate::records::RecoveryGrants::default(),
249 }
250 }
251
252 /// The context command for one print.
253 #[must_use]
254 pub fn context_command_for(&self, print_id: PrintId) -> String {
255 self.context_command
256 .replace(PRINT_ID_PLACEHOLDER, &print_id.to_string())
257 }
258}