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_types::{EventRecord, ImageRef, PrintId, Timestamp};
20
21use crate::gcode_index::GcodeIndex;
22use crate::records::PrintRecord;
23use crate::supervisor::Supervisor;
24
25/// What a check's image is asked for.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum ImageUse {
28 /// The image attached to a supervision turn's prompt: the print's next
29 /// check is shown this one's frame as the previous.
30 Check,
31 /// The image a look answers, which moves no check along.
32 Look,
33}
34
35/// Where a print stood in its own G-code: the index of its file, and the
36/// job's file position in it.
37#[derive(Debug, Clone)]
38pub struct PlanPosition {
39 /// The print's G-code index.
40 pub index: Arc<GcodeIndex>,
41 /// The job's file position, in bytes.
42 pub file_position_bytes: u64,
43}
44
45/// One request for a check's image of a stored frame.
46#[derive(Debug, Clone)]
47pub struct CheckImageRequest<'a> {
48 /// The print the image is of; none for a look at the printer.
49 pub print_id: Option<PrintId>,
50 /// Where the stored frame is.
51 pub frame: &'a Path,
52 /// When the frame was captured.
53 pub captured_at: Timestamp,
54 /// What the image is for.
55 pub made_for: ImageUse,
56 /// Where the print stood in its G-code, when its job is its own file and
57 /// reported a position the index was read for.
58 pub plan: Option<PlanPosition>,
59}
60
61/// A check's image, and the line saying what it is.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct ShownImage {
64 /// The image's path.
65 pub path: PathBuf,
66 /// What the image is, and why it is that one, in one line; none when what
67 /// made it says nothing.
68 pub note: Option<String>,
69 /// Whether it is the three-panel image, drawn from the print's plan,
70 /// rather than a frame as the camera took it or scaled whole.
71 pub composite: bool,
72}
73
74/// What makes a check's image of one stored frame.
75pub trait CheckImages: Send + Sync {
76 /// The path of the image a check of `print_id` — or a look at the printer,
77 /// when it names none — is shown of the frame stored at `frame`, or why
78 /// none could be made.
79 ///
80 /// # Errors
81 ///
82 /// Answers why the image could not be made: the frame unreadable, or the
83 /// image unwritable.
84 fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String>;
85
86 /// The image one request is shown and the line saying what it is: by
87 /// default [`check_image`](Self::check_image)'s, saying nothing.
88 ///
89 /// # Errors
90 ///
91 /// As [`check_image`](Self::check_image)'s.
92 fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
93 self.check_image(request.print_id, request.frame)
94 .map(|path| ShownImage {
95 path,
96 note: None,
97 composite: false,
98 })
99 }
100
101 /// Whether a check of `print_id` would be shown the three-panel image of a
102 /// frame from the server's own camera: by default, never.
103 fn composes(&self, print_id: PrintId) -> bool {
104 let _ = print_id;
105 false
106 }
107
108 /// Measure `print_id`'s growth only from frames checked after now: it
109 /// waited at a planned change, and a frame from before the wait would
110 /// count the wait as no growth. By default there is nothing to forget.
111 fn restart_growth(&self, print_id: PrintId) {
112 let _ = print_id;
113 }
114}
115
116/// When an event's frame was captured: what the arrival knew, else what its
117/// payload says, else when the event was received.
118pub(crate) fn captured_at_of(event: &EventRecord, known: Option<Timestamp>) -> Timestamp {
119 known
120 .or_else(|| {
121 event
122 .body
123 .payload
124 .get("frame_captured_at")
125 .cloned()
126 .and_then(|value| printobserver_types::serde_json::from_value(value).ok())
127 })
128 .unwrap_or(event.received_at)
129}
130
131impl Supervisor {
132 /// Install what makes every check's image. The first installation stands;
133 /// answers whether this one did.
134 pub fn install_check_images(&self, images: std::sync::Arc<dyn CheckImages>) -> bool {
135 self.check_images.set(images).is_ok()
136 }
137
138 /// Where a print stood in its own G-code by a job read: nothing when the
139 /// job runs another file, reported no position, or the file has no index.
140 pub(crate) async fn plan_position(
141 &self,
142 print: &PrintRecord,
143 job: Option<&JobSnapshot>,
144 ) -> Option<PlanPosition> {
145 let job = job?;
146 if job.file_name.is_none() || job.file_name != print.file_name {
147 return None;
148 }
149 let file_position_bytes = u64::try_from(job.file_position_bytes?).ok()?;
150 let index = self.print_gcode_index(print.id).await?;
151 Some(PlanPosition {
152 index,
153 file_position_bytes,
154 })
155 }
156
157 /// The image a check is shown of one stored frame, and the line saying
158 /// what it is: the stored frame itself when nothing that makes one is
159 /// installed, or when what is installed could not make it, which is a
160 /// check shown more than it needs rather than a check shown nothing.
161 pub(crate) async fn shown_image_of(
162 &self,
163 image: &ImageRef,
164 print_id: Option<PrintId>,
165 captured_at: Timestamp,
166 made_for: ImageUse,
167 plan: Option<PlanPosition>,
168 ) -> Option<ShownImage> {
169 let stored = self.image_path(image).await?;
170 let Some(images) = self.check_images.get() else {
171 return Some(ShownImage {
172 path: stored,
173 note: None,
174 composite: false,
175 });
176 };
177 let request = CheckImageRequest {
178 print_id,
179 frame: &stored,
180 captured_at,
181 made_for,
182 plan,
183 };
184 Some(
185 images
186 .shown_image(&request)
187 .unwrap_or_else(|error| ShownImage {
188 note: Some(format!(
189 "the frame as the camera took it, because its check image could not be made: {error}"
190 )),
191 path: stored.clone(),
192 composite: false,
193 }),
194 )
195 }
196}