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}
71
72/// A check's image, and the line saying what it is.
73#[derive(Debug, Clone, PartialEq)]
74pub struct ShownImage {
75 /// The image's path.
76 pub path: PathBuf,
77 /// What the image is, and why it is that one, in one line; none when what
78 /// made it says nothing.
79 pub note: Option<String>,
80 /// Whether it is the three-panel image, drawn from the print's plan,
81 /// rather than a frame as the camera took it or scaled whole.
82 pub composite: bool,
83 /// Why it is the whole frame, when it is and what made it gave a reason.
84 pub fallback: Option<ImageFallback>,
85 /// What was judged of the frame making the image, each to be appended to
86 /// the request's print's history in this order. Each names the stored
87 /// frame it was made on.
88 pub records: Vec<EventBody>,
89}
90
91impl ShownImage {
92 /// An image that is a frame as it is, with nothing judged of it.
93 #[must_use]
94 pub const fn plain(path: PathBuf, note: Option<String>) -> Self {
95 Self {
96 path,
97 note,
98 composite: false,
99 fallback: None,
100 records: Vec::new(),
101 }
102 }
103
104 /// Which image it is.
105 #[must_use]
106 pub const fn kind(&self) -> ImageKind {
107 if self.composite {
108 ImageKind::ThreePanel
109 } else {
110 ImageKind::WholeFrame
111 }
112 }
113}
114
115/// What makes a check's image of one stored frame.
116pub trait CheckImages: Send + Sync {
117 /// The path of the image a check of `print_id` — or a look at the printer,
118 /// when it names none — is shown of the frame stored at `frame`, or why
119 /// none could be made.
120 ///
121 /// # Errors
122 ///
123 /// Answers why the image could not be made: the frame unreadable, or the
124 /// image unwritable.
125 fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String>;
126
127 /// The image one request is shown and the line saying what it is: by
128 /// default [`check_image`](Self::check_image)'s, saying nothing.
129 ///
130 /// # Errors
131 ///
132 /// As [`check_image`](Self::check_image)'s.
133 fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
134 self.check_image(request.print_id, request.frame)
135 .map(|path| ShownImage::plain(path, None))
136 }
137
138 /// Whether a check of `print_id` would be shown the three-panel image of a
139 /// frame from the server's own camera: by default, never.
140 fn composes(&self, print_id: PrintId) -> bool {
141 let _ = print_id;
142 false
143 }
144
145 /// Measure `print_id`'s growth only from frames checked after now: it
146 /// waited at a planned change, and a frame from before the wait would
147 /// count the wait as no growth. By default there is nothing to forget.
148 fn restart_growth(&self, print_id: PrintId) {
149 let _ = print_id;
150 }
151}
152
153/// When an event's frame was captured: what the arrival knew, else what its
154/// payload says, else when the event was received.
155pub(crate) fn captured_at_of(event: &EventRecord, known: Option<Timestamp>) -> Timestamp {
156 known
157 .or_else(|| {
158 event
159 .body
160 .payload
161 .get("frame_captured_at")
162 .cloned()
163 .and_then(|value| printobserver_types::serde_json::from_value(value).ok())
164 })
165 .unwrap_or(event.received_at)
166}
167
168/// What re-judging a print's camera needs, read now.
169#[derive(Debug, Clone)]
170pub struct FreshView {
171 /// A good frame from the configured camera, not yet stored, and the URL
172 /// it came from; none when no camera is configured or none came.
173 pub frame: Option<(String, printobserver_vision_api::FetchedImage)>,
174 /// Where the print stands in its own G-code, when it is open and its job
175 /// is its own file.
176 pub plan: Option<PlanPosition>,
177 /// Whether the printer reports the print paused.
178 pub paused: bool,
179}
180
181impl Supervisor {
182 /// Read what re-judging one print's camera needs, now: a fresh frame,
183 /// where the print stands in its plan, and whether it is paused. Nothing
184 /// is written and nothing is asked of the printer but two reads.
185 ///
186 /// # Errors
187 ///
188 /// [`CoreError::NoSuchPrint`](crate::CoreError::NoSuchPrint) when nothing
189 /// is held under that identifier, and the store's own error when the print
190 /// could not be read.
191 pub async fn fresh_view(&self, print_id: PrintId) -> Result<FreshView, crate::CoreError> {
192 let print = self
193 .stores()
194 .prints
195 .print(print_id)
196 .await?
197 .ok_or(crate::CoreError::NoSuchPrint { print_id })?;
198 let job = self.read_job().await.ok();
199 let paused = self
200 .read_snapshot()
201 .await
202 .is_ok_and(|taken| taken.connection == printobserver_types::PrinterState::Paused);
203 let plan = if print.ended_at.is_none() {
204 self.plan_position(&print, job.as_ref()).await
205 } else {
206 None
207 };
208 let frame = self.fetch_camera_image(print_id).await;
209 Ok(FreshView {
210 frame,
211 plan,
212 paused,
213 })
214 }
215
216 /// Install what makes every check's image. The first installation stands;
217 /// answers whether this one did.
218 pub fn install_check_images(&self, images: std::sync::Arc<dyn CheckImages>) -> bool {
219 self.check_images.set(images).is_ok()
220 }
221
222 /// Where a print stood in its own G-code by a job read: nothing when the
223 /// job runs another file, reported no position, or the file has no index.
224 pub(crate) async fn plan_position(
225 &self,
226 print: &PrintRecord,
227 job: Option<&JobSnapshot>,
228 ) -> Option<PlanPosition> {
229 let job = job?;
230 if job.file_name.is_none() || job.file_name != print.file_name {
231 return None;
232 }
233 let file_position_bytes = u64::try_from(job.file_position_bytes?).ok()?;
234 let index = self.print_gcode_index(print.id).await?;
235 Some(PlanPosition {
236 index,
237 file_position_bytes,
238 })
239 }
240
241 /// The image a check is shown of one stored frame, and the line saying
242 /// what it is: the stored frame itself when nothing that makes one is
243 /// installed, or when what is installed could not make it, which is a
244 /// check shown more than it needs rather than a check shown nothing.
245 #[expect(
246 clippy::too_many_arguments,
247 reason = "each is one fact of the request the installed images are asked"
248 )]
249 pub(crate) async fn shown_image_of(
250 &self,
251 image: &ImageRef,
252 print_id: Option<PrintId>,
253 captured_at: Timestamp,
254 made_for: ImageUse,
255 plan: Option<PlanPosition>,
256 own_camera: bool,
257 paused: bool,
258 ) -> Option<ShownImage> {
259 let stored = self.image_path(image).await?;
260 let Some(images) = self.check_images.get() else {
261 return Some(ShownImage::plain(stored, None));
262 };
263 let request = CheckImageRequest {
264 print_id,
265 frame: &stored,
266 frame_sha256: &image.sha256,
267 captured_at,
268 made_for,
269 plan,
270 own_camera,
271 paused,
272 };
273 let mut shown = images.shown_image(&request).unwrap_or_else(|error| {
274 let message = format!("its check image could not be made: {error}");
275 ShownImage {
276 note: Some(format!(
277 "the frame as the camera took it, because {message}"
278 )),
279 fallback: Some(ImageFallback {
280 code: printobserver_supervisor_api::WholeFrameReasonCode::Refused,
281 message,
282 }),
283 ..ShownImage::plain(stored.clone(), None)
284 }
285 });
286 // What was judged of the frame is the print's record, each naming the
287 // stored frame it was made on. A record the store refuses is said on
288 // the log and costs the check nothing: the image is shown either way.
289 for body in std::mem::take(&mut shown.records) {
290 let kind = body.kind.clone();
291 if let Err(error) = self.write_body_with_frame(print_id, body, None).await {
292 eprintln!("printobserver: a {kind} record could not be written: {error}");
293 }
294 }
295 Some(shown)
296 }
297}