Skip to main content

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}
70
71/// What makes a check's image of one stored frame.
72pub trait CheckImages: Send + Sync {
73    /// The path of the image a check of `print_id` — or a look at the printer,
74    /// when it names none — is shown of the frame stored at `frame`, or why
75    /// none could be made.
76    ///
77    /// # Errors
78    ///
79    /// Answers why the image could not be made: the frame unreadable, or the
80    /// image unwritable.
81    fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String>;
82
83    /// The image one request is shown and the line saying what it is: by
84    /// default [`check_image`](Self::check_image)'s, saying nothing.
85    ///
86    /// # Errors
87    ///
88    /// As [`check_image`](Self::check_image)'s.
89    fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
90        self.check_image(request.print_id, request.frame)
91            .map(|path| ShownImage { path, note: None })
92    }
93}
94
95/// When an event's frame was captured: what the arrival knew, else what its
96/// payload says, else when the event was received.
97pub(crate) fn captured_at_of(event: &EventRecord, known: Option<Timestamp>) -> Timestamp {
98    known
99        .or_else(|| {
100            event
101                .body
102                .payload
103                .get("frame_captured_at")
104                .cloned()
105                .and_then(|value| printobserver_types::serde_json::from_value(value).ok())
106        })
107        .unwrap_or(event.received_at)
108}
109
110impl Supervisor {
111    /// Install what makes every check's image. The first installation stands;
112    /// answers whether this one did.
113    pub fn install_check_images(&self, images: std::sync::Arc<dyn CheckImages>) -> bool {
114        self.check_images.set(images).is_ok()
115    }
116
117    /// Where a print stood in its own G-code by a job read: nothing when the
118    /// job runs another file, reported no position, or the file has no index.
119    pub(crate) async fn plan_position(
120        &self,
121        print: &PrintRecord,
122        job: Option<&JobSnapshot>,
123    ) -> Option<PlanPosition> {
124        let job = job?;
125        if job.file_name.is_none() || job.file_name != print.file_name {
126            return None;
127        }
128        let file_position_bytes = u64::try_from(job.file_position_bytes?).ok()?;
129        let index = self.print_gcode_index(print.id).await?;
130        Some(PlanPosition {
131            index,
132            file_position_bytes,
133        })
134    }
135
136    /// The image a check is shown of one stored frame, and the line saying
137    /// what it is: the stored frame itself when nothing that makes one is
138    /// installed, or when what is installed could not make it, which is a
139    /// check shown more than it needs rather than a check shown nothing.
140    pub(crate) async fn shown_image_of(
141        &self,
142        image: &ImageRef,
143        print_id: Option<PrintId>,
144        captured_at: Timestamp,
145        made_for: ImageUse,
146        plan: Option<PlanPosition>,
147    ) -> Option<ShownImage> {
148        let stored = self.image_path(image).await?;
149        let Some(images) = self.check_images.get() else {
150            return Some(ShownImage {
151                path: stored,
152                note: None,
153            });
154        };
155        let request = CheckImageRequest {
156            print_id,
157            frame: &stored,
158            captured_at,
159            made_for,
160            plan,
161        };
162        Some(
163            images
164                .shown_image(&request)
165                .unwrap_or_else(|error| ShownImage {
166                    note: Some(format!(
167                        "the frame as the camera took it, because its check image could not be made: {error}"
168                    )),
169                    path: stored.clone(),
170                }),
171        )
172    }
173}