printobserver_core/check_image.rs
1//! The image a check is shown, chosen in one place.
2//!
3//! A frame is stored at the size the camera took it, and the operator's own
4//! image read serves exactly that. What a supervision turn is shown — the
5//! image attached to its prompt and the image a look answers — is whatever the
6//! installed [`CheckImages`] makes of the stored frame, because every call of a
7//! turn re-sends the images it holds. With none installed, a check is shown the
8//! stored frame itself.
9//!
10//! What makes the image is told what it is for — a check, or a look — and
11//! where the print stood in its own G-code when the check began, so that it can
12//! draw that plan on the frame; it answers the image and one line saying what
13//! that image is, which the turn's prompt carries.
14
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18use printobserver_printer_api::JobSnapshot;
19use printobserver_supervisor_api::{ImageFallback, ImageKind};
20use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId, Timestamp};
21
22use crate::gcode_index::GcodeIndex;
23use crate::records::PrintRecord;
24use crate::supervisor::Supervisor;
25
26/// What a check's image is asked for.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum ImageUse {
29 /// The image attached to a supervision turn's prompt: the print's next
30 /// check is shown this one's frame as the previous.
31 Check,
32 /// The image a look answers, which moves no check along.
33 Look,
34}
35
36/// Where a print stood in its own G-code: the index of its file, and the
37/// job's file position in it.
38#[derive(Debug, Clone)]
39pub struct PlanPosition {
40 /// The print's G-code index.
41 pub index: Arc<GcodeIndex>,
42 /// The job's file position, in bytes.
43 pub file_position_bytes: u64,
44}
45
46/// One request for a check's image of a stored frame.
47#[derive(Debug, Clone)]
48pub struct CheckImageRequest<'a> {
49 /// The print the image is of; none for a look at the printer.
50 pub print_id: Option<PrintId>,
51 /// Where the stored frame is.
52 pub frame: &'a Path,
53 /// The stored frame's SHA-256, as the image store names it: what a record
54 /// of a judgement made on it names.
55 pub frame_sha256: &'a str,
56 /// Whether the frame is the configured camera's own rather than a
57 /// detector's picture: only the camera's own frames are judged against its
58 /// calibration.
59 pub own_camera: bool,
60 /// Whether the printer reported the print paused as the check began, its
61 /// bed moved off the plan's height.
62 pub paused: bool,
63 /// When the frame was captured.
64 pub captured_at: Timestamp,
65 /// What the image is for.
66 pub made_for: ImageUse,
67 /// Where the print stood in its G-code, when its job is its own file and
68 /// reported a position the index was read for.
69 pub plan: Option<PlanPosition>,
70 /// The record of the camera check the print started under, which it is
71 /// drawn through from its first check; none when it started under none,
72 /// or for a look at the printer.
73 pub camera_check: Option<EventRecord>,
74}
75
76/// A check's image, and the line saying what it is.
77#[derive(Debug, Clone, PartialEq)]
78pub struct ShownImage {
79 /// The image's path.
80 pub path: PathBuf,
81 /// What the image is, and why it is that one, in one line; none when what
82 /// made it says nothing.
83 pub note: Option<String>,
84 /// Whether it is the three-panel image, drawn from the print's plan,
85 /// rather than a frame as the camera took it or scaled whole.
86 pub composite: bool,
87 /// Why it is the whole frame, when it is and what made it gave a reason.
88 pub fallback: Option<ImageFallback>,
89 /// What was judged of the frame making the image, each to be appended to
90 /// the request's print's history in this order. Each names the stored
91 /// frame it was made on.
92 pub records: Vec<EventBody>,
93}
94
95impl ShownImage {
96 /// An image that is a frame as it is, with nothing judged of it.
97 #[must_use]
98 pub const fn plain(path: PathBuf, note: Option<String>) -> Self {
99 Self {
100 path,
101 note,
102 composite: false,
103 fallback: None,
104 records: Vec::new(),
105 }
106 }
107
108 /// Which image it is.
109 #[must_use]
110 pub const fn kind(&self) -> ImageKind {
111 if self.composite {
112 ImageKind::ThreePanel
113 } else {
114 ImageKind::WholeFrame
115 }
116 }
117}
118
119/// What makes a check's image of one stored frame.
120pub trait CheckImages: Send + Sync {
121 /// The path of the image a check of `print_id` — or a look at the printer,
122 /// when it names none — is shown of the frame stored at `frame`, or why
123 /// none could be made.
124 ///
125 /// # Errors
126 ///
127 /// Answers why the image could not be made: the frame unreadable, or the
128 /// image unwritable.
129 fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String>;
130
131 /// The image one request is shown and the line saying what it is: by
132 /// default [`check_image`](Self::check_image)'s, saying nothing.
133 ///
134 /// # Errors
135 ///
136 /// As [`check_image`](Self::check_image)'s.
137 fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
138 self.check_image(request.print_id, request.frame)
139 .map(|path| ShownImage::plain(path, None))
140 }
141
142 /// Whether a check of `print_id` would be shown the three-panel image of a
143 /// frame from the server's own camera: by default, never.
144 fn composes(&self, print_id: PrintId) -> bool {
145 let _ = print_id;
146 false
147 }
148
149 /// Measure `print_id`'s growth only from frames checked after now: it
150 /// waited at a planned change, and a frame from before the wait would
151 /// count the wait as no growth. By default there is nothing to forget.
152 fn restart_growth(&self, print_id: PrintId) {
153 let _ = print_id;
154 }
155}
156
157/// When an event's frame was captured: what the arrival knew, else what its
158/// payload says, else when the event was received.
159pub(crate) fn captured_at_of(event: &EventRecord, known: Option<Timestamp>) -> Timestamp {
160 known
161 .or_else(|| {
162 event
163 .body
164 .payload
165 .get("frame_captured_at")
166 .cloned()
167 .and_then(|value| printobserver_types::serde_json::from_value(value).ok())
168 })
169 .unwrap_or(event.received_at)
170}
171
172/// What re-judging a print's camera needs, read now.
173#[derive(Debug, Clone)]
174pub struct FreshView {
175 /// A good frame from the configured camera, not yet stored, and the URL
176 /// it came from; none when no camera is configured or none came.
177 pub frame: Option<(String, printobserver_vision_api::FetchedImage)>,
178 /// Where the print stands in its own G-code, when it is open and its job
179 /// is its own file.
180 pub plan: Option<PlanPosition>,
181 /// Whether the printer reports the print paused.
182 pub paused: bool,
183 /// The record of the camera check the print started under, when it
184 /// started under one.
185 pub camera_check: Option<EventRecord>,
186}
187
188impl Supervisor {
189 /// Read what re-judging one print's camera needs, now: a fresh frame,
190 /// where the print stands in its plan, and whether it is paused. Nothing
191 /// is written and nothing is asked of the printer but two reads.
192 ///
193 /// # Errors
194 ///
195 /// [`CoreError::NoSuchPrint`](crate::CoreError::NoSuchPrint) when nothing
196 /// is held under that identifier, and the store's own error when the print
197 /// could not be read.
198 pub async fn fresh_view(&self, print_id: PrintId) -> Result<FreshView, crate::CoreError> {
199 let print = self
200 .stores()
201 .prints
202 .print(print_id)
203 .await?
204 .ok_or(crate::CoreError::NoSuchPrint { print_id })?;
205 let job = self.read_job().await.ok();
206 let paused = self
207 .read_snapshot()
208 .await
209 .is_ok_and(|taken| taken.connection == printobserver_types::PrinterState::Paused);
210 let plan = if print.ended_at.is_none() {
211 self.plan_position(&print, job.as_ref()).await
212 } else {
213 None
214 };
215 let frame = self.fetch_camera_image(print_id).await;
216 let camera_check = self.print_camera_check(print_id).await;
217 Ok(FreshView {
218 frame,
219 plan,
220 paused,
221 camera_check,
222 })
223 }
224
225 /// The record of the camera check one print started under: the one its
226 /// `print_started` names, which the start held to being `aligned` on the
227 /// manifest's sheet — never a manifest written afterwards, which no start
228 /// checked. None when it names none, or when the log cannot be read, which
229 /// leaves the print drawn as one naming none is.
230 pub(crate) async fn print_camera_check(&self, print_id: PrintId) -> Option<EventRecord> {
231 let named = self.print_started_of(print_id).await.ok()??.camera_check?;
232 self.camera_check_record(named).await.ok().flatten()
233 }
234
235 /// Install what makes every check's image. The first installation stands;
236 /// answers whether this one did.
237 pub fn install_check_images(&self, images: std::sync::Arc<dyn CheckImages>) -> bool {
238 self.check_images.set(images).is_ok()
239 }
240
241 /// Where a print stood in its own G-code by a job read: nothing when the
242 /// job runs another file, reported no position, or the file has no index.
243 pub(crate) async fn plan_position(
244 &self,
245 print: &PrintRecord,
246 job: Option<&JobSnapshot>,
247 ) -> Option<PlanPosition> {
248 let job = job?;
249 if job.file_name.is_none() || job.file_name != print.file_name {
250 return None;
251 }
252 let file_position_bytes = u64::try_from(job.file_position_bytes?).ok()?;
253 let index = self.print_gcode_index(print.id).await?;
254 Some(PlanPosition {
255 index,
256 file_position_bytes,
257 })
258 }
259
260 /// The image a check is shown of one stored frame, and the line saying
261 /// what it is: the stored frame itself when nothing that makes one is
262 /// installed, or when what is installed could not make it, which is a
263 /// check shown more than it needs rather than a check shown nothing.
264 #[expect(
265 clippy::too_many_arguments,
266 reason = "each is one fact of the request the installed images are asked"
267 )]
268 pub(crate) async fn shown_image_of(
269 &self,
270 image: &ImageRef,
271 print_id: Option<PrintId>,
272 captured_at: Timestamp,
273 made_for: ImageUse,
274 plan: Option<PlanPosition>,
275 own_camera: bool,
276 paused: bool,
277 ) -> Option<ShownImage> {
278 let stored = self.image_path(image).await?;
279 let Some(images) = self.check_images.get() else {
280 return Some(ShownImage::plain(stored, None));
281 };
282 let camera_check = match print_id {
283 Some(print_id) => self.print_camera_check(print_id).await,
284 None => None,
285 };
286 let request = CheckImageRequest {
287 print_id,
288 camera_check,
289 frame: &stored,
290 frame_sha256: &image.sha256,
291 captured_at,
292 made_for,
293 plan,
294 own_camera,
295 paused,
296 };
297 let mut shown = images.shown_image(&request).unwrap_or_else(|error| {
298 let message = format!("its check image could not be made: {error}");
299 ShownImage {
300 note: Some(format!(
301 "the frame as the camera took it, because {message}"
302 )),
303 fallback: Some(ImageFallback {
304 code: printobserver_supervisor_api::WholeFrameReasonCode::Refused,
305 message,
306 }),
307 ..ShownImage::plain(stored.clone(), None)
308 }
309 });
310 // What was judged of the frame is the print's record, each naming the
311 // stored frame it was made on. A record the store refuses is said on
312 // the log and costs the check nothing: the image is shown either way.
313 for body in std::mem::take(&mut shown.records) {
314 let kind = body.kind.clone();
315 if let Err(error) = self.write_body_with_frame(print_id, body, None).await {
316 eprintln!("printobserver: a {kind} record could not be written: {error}");
317 }
318 }
319 Some(shown)
320 }
321}