Skip to main content

printobserver_core/
planned.rs

1//! A print waiting at a change its own G-code plans.
2//!
3//! A single-nozzle print sliced with colour changes stops at each `M600` so a
4//! person can load the next colour, and at an `M601` so a person can do
5//! whatever the pause was planned for. To everything else this supervisor
6//! watches that wait looks like a stall: the file position freezes, the parts
7//! stop growing, and the firmware's idle timeout turns the nozzle target to
8//! zero. So a planned stop is recognised, and the print is left alone until it
9//! carries on.
10//!
11//! # Reached
12//!
13//! A change is reached when a filament-change signal arrives with the job at
14//! it, or a read of the job finds its file position at the change's line or
15//! just past it ([`GcodeIndex::change_waiting_at`]). Either writes one
16//! [`FilamentChangePlannedReachedPayload`] per change of a print, and charges
17//! the spool on tool 0 up to the change's own offset, with the
18//! `filament_change_signalled` that is the accounting record of every change.
19//! A filament-change signal arriving again for a change already reached —
20//! `Obico` repeats one every ten minutes while the printer waits — writes
21//! nothing of its own and starts nothing.
22//!
23//! # While it waits
24//!
25//! No supervision turn runs for the print: no alert's, no scheduled check's
26//! and none the printer watch would give. A pause, a resume or an adjustment
27//! from any actor is refused
28//! [`PlannedChangeWaiting`](crate::records::RejectionReason::PlannedChangeWaiting);
29//! a cancel and every spool command are not, because a person may abandon the
30//! print or load the next spool while it waits.
31//!
32//! # Resumed
33//!
34//! When a read finds the file position past the change, one
35//! [`FilamentChangePlannedResumedPayload`] is written with the camera's frame,
36//! and that event is the print's next check, at once. The growth measurement
37//! starts again from frames taken after it, and the print's next scheduled
38//! check is one observation interval after it.
39//!
40//! # What is remembered, and where
41//!
42//! The store's history is the record; this supervisor keeps a copy of each
43//! print's planned changes so an alert or a request asks nothing of the store
44//! for a print whose file plans none. A print's copy is read from the history
45//! the first time its index, once built, plans a change, and for every open
46//! print as the server starts ([`Supervisor::restore_planned_changes`]).
47//! The index of a print found open as the server starts is built by the
48//! first read of its running job the printer watch makes, once, so a
49//! restarted server reaches a change by position before any check of it.
50
51use std::collections::{BTreeMap, BTreeSet};
52use std::sync::PoisonError;
53use std::time::Duration;
54
55use printobserver_printer_api::{JobSnapshot, PrinterState};
56use printobserver_types::{EventBody, EventKind, EventPayload, EventRecord, PrintId, Timestamp};
57
58use crate::accounting::{Whereabouts, spool_on_tool};
59use crate::clock::seconds_between;
60use crate::error::CoreError;
61use crate::events::PendingTurn;
62use crate::gcode_index::{GcodeIndex, PlannedChange, PlannedChanges};
63use crate::inbox::{AlertCameraFrame, Arrival};
64use crate::kinds::{
65    FilamentChangePlannedReachedPayload, FilamentChangePlannedResumedPayload, PlannedChangeTrigger,
66};
67use crate::look::Frame;
68use crate::records::{ActionKind, FilePosition, PrintRecord, RejectionReason};
69use crate::store::{HistoryQuery, MAX_HISTORY_LIMIT};
70use crate::supervisor::Supervisor;
71
72/// The actions a print waiting at a planned change refuses, whoever asks.
73pub const REFUSED_WHILE_WAITING: [ActionKind; 7] = [
74    ActionKind::Pause,
75    ActionKind::Resume,
76    ActionKind::SetFeedrateFactor,
77    ActionKind::SetFlowrateFactor,
78    ActionKind::SetToolTargetC,
79    ActionKind::SetBedTargetC,
80    ActionKind::SetFanPercent,
81];
82
83/// The change a print is waiting at, as its `reached` recorded it.
84#[derive(Debug, Clone, PartialEq)]
85pub struct Waiting {
86    /// What the `reached` event recorded.
87    pub reached: FilamentChangePlannedReachedPayload,
88    /// When it was recorded.
89    pub since: Timestamp,
90}
91
92impl Waiting {
93    /// The refusal a pause, a resume or an adjustment is answered while it
94    /// waits.
95    #[must_use]
96    pub fn refusal(&self) -> RejectionReason {
97        let change = &self.reached.change;
98        RejectionReason::PlannedChangeWaiting {
99            change_index: change.index,
100            layer: change.layer,
101            z_mm: change.z_mm,
102            color: change.color.clone(),
103        }
104    }
105}
106
107/// What this supervisor holds of one print's planned changes.
108#[derive(Debug, Clone, Default)]
109pub(crate) struct PlannedMemo {
110    /// Every change of the print's reached so far, by index.
111    reached: BTreeSet<u32>,
112    /// The change it is waiting at now.
113    waiting: Option<Waiting>,
114}
115
116/// One print's planned changes as its history records them, newest first.
117fn memo_of(history: &[EventRecord]) -> PlannedMemo {
118    let mut memo = PlannedMemo::default();
119    let mut resumed = BTreeSet::new();
120    for event in history.iter().rev() {
121        if let Some(Ok(reached)) = event.payload_as::<FilamentChangePlannedReachedPayload>() {
122            memo.reached.insert(reached.change.index);
123            memo.waiting = Some(Waiting {
124                reached,
125                since: event.received_at,
126            });
127        } else if let Some(Ok(done)) = event.payload_as::<FilamentChangePlannedResumedPayload>() {
128            resumed.insert(done.change.index);
129        }
130    }
131    memo.waiting = memo
132        .waiting
133        .filter(|waiting| !resumed.contains(&waiting.reached.change.index));
134    memo
135}
136
137/// How long a job read paused at a planned change stands at one position
138/// before that position alone reaches the change: long enough for the
139/// filament-change signal a pause there brings to arrive first, and well inside
140/// the interval between two scheduled checks.
141pub(crate) const PAUSED_AT_CHANGE_STAND: Duration = Duration::from_secs(30);
142
143/// The file position a job read reports for a print, when the job is that
144/// print's file, printing or paused, and reports one.
145fn position_of(print: &PrintRecord, job: &JobSnapshot) -> Option<u64> {
146    let running = matches!(job.state, PrinterState::Printing | PrinterState::Paused);
147    let same_file = print.file_name.is_none() || job.file_name == print.file_name;
148    job.file_position_bytes
149        .filter(|_| running && same_file)
150        .and_then(|bytes| u64::try_from(bytes).ok())
151}
152
153/// Whether an index plans any change.
154fn plans_changes(index: &GcodeIndex) -> bool {
155    index.planned_change(0).is_some()
156}
157
158impl Supervisor {
159    /// The memo of one print's planned changes, read from its history when
160    /// this supervisor holds none and its index, built, plans a change.
161    async fn planned_memo(&self, print_id: PrintId) -> Result<Option<PlannedMemo>, CoreError> {
162        if let Some(memo) = self.planned_memos().get(&print_id) {
163            return Ok(Some(memo.clone()));
164        }
165        let plans = self
166            .gcode_indexes()
167            .built(print_id)
168            .is_some_and(|index| plans_changes(&index));
169        if !plans {
170            return Ok(None);
171        }
172        self.load_planned_memo(print_id).await.map(Some)
173    }
174
175    /// Read one print's planned changes from its history into the memo.
176    async fn load_planned_memo(&self, print_id: PrintId) -> Result<PlannedMemo, CoreError> {
177        let kinds = [
178            FilamentChangePlannedReachedPayload::KIND,
179            FilamentChangePlannedResumedPayload::KIND,
180        ]
181        .into_iter()
182        .filter_map(|kind| EventKind::new(kind).ok())
183        .collect();
184        let history = self
185            .stores()
186            .events
187            .history(HistoryQuery {
188                print_id,
189                kinds,
190                since: None,
191                until: None,
192                limit: Some(MAX_HISTORY_LIMIT),
193            })
194            .await?;
195        let memo = memo_of(&history);
196        self.planned_memos().insert(print_id, memo.clone());
197        Ok(memo)
198    }
199
200    /// The memos, held for one read or write.
201    fn planned_memos(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, PlannedMemo>> {
202        self.planned_memos
203            .lock()
204            .unwrap_or_else(PoisonError::into_inner)
205    }
206
207    /// Read every open print's planned changes from the history, as a server
208    /// starts: a print that was waiting at a change when the last one stopped
209    /// is still waiting at it, and is left alone from the first read on.
210    ///
211    /// # Errors
212    ///
213    /// The store's own error when the open prints or a history could not be
214    /// read.
215    pub async fn restore_planned_changes(&self) -> Result<(), CoreError> {
216        for print in self.stores().prints.open_prints().await? {
217            self.load_planned_memo(print.id).await?;
218            self.index_owed
219                .lock()
220                .unwrap_or_else(PoisonError::into_inner)
221                .insert(print.id);
222        }
223        Ok(())
224    }
225
226    /// The planned change one print is waiting at, when it is waiting at one.
227    ///
228    /// # Errors
229    ///
230    /// The store's own error when the print's history had to be read and
231    /// could not be.
232    pub async fn planned_change_waiting(
233        &self,
234        print_id: PrintId,
235    ) -> Result<Option<Waiting>, CoreError> {
236        Ok(self
237            .planned_memo(print_id)
238            .await?
239            .and_then(|memo| memo.waiting))
240    }
241
242    /// One print's planned changes, the one it waits at and the colour
243    /// expected where its job stands, as the status read answers them:
244    /// nothing for a print whose file plans none or could not be read.
245    ///
246    /// # Errors
247    ///
248    /// The store's own error when the print's history could not be read.
249    pub async fn planned_changes(
250        &self,
251        print: &PrintRecord,
252        job: Option<&JobSnapshot>,
253    ) -> Result<Option<PlannedChanges>, CoreError> {
254        if print.ended_at.is_some() {
255            return Ok(None);
256        }
257        let Some(index) = self.print_gcode_index(print.id).await else {
258            return Ok(None);
259        };
260        if !plans_changes(&index) {
261            return Ok(None);
262        }
263        let waiting = self.planned_change_waiting(print.id).await?;
264        let position = job.and_then(|job| position_of(print, job));
265        Ok(Some(PlannedChanges {
266            changes: index.planned_changes(),
267            segments: index.planned_segments(),
268            waiting: waiting.map(|waiting| waiting.reached.change.index),
269            expected_color: position.and_then(|position| {
270                index.expected_color_at(i64::try_from(position).unwrap_or(i64::MAX))
271            }),
272        }))
273    }
274
275    /// Whether a print may be given a supervision turn now: not while it
276    /// waits at a planned change.
277    pub(crate) async fn turns_allowed(&self, print_id: PrintId) -> Result<bool, CoreError> {
278        Ok(self.planned_change_waiting(print_id).await?.is_none())
279    }
280
281    /// Follow one read of a print's job against the changes its file plans:
282    /// record a change it has reached, or one it has carried on from, and
283    /// answer the check carrying on claims.
284    ///
285    /// A print a restart found open, whose index this supervisor has not
286    /// built, has its index built here when `build` asks, once per print: the
287    /// printer watch asks, so a change is reached by position from the first
288    /// read of the job after a restart, with no check or signal to build it
289    /// first. A scheduled check does not, so it is recorded as it begins
290    /// rather than after a whole file is read; it builds the index itself. A
291    /// print this supervisor started is never read here: its index is built
292    /// by its first check, as it always was, so a start whose preflight is off
293    /// reads nothing of its file. A build that fails is left to the next
294    /// check, as every failed build is.
295    ///
296    /// # Errors
297    ///
298    /// The store's own error when what changed could not be recorded.
299    pub(crate) async fn follow_planned_changes(
300        &self,
301        print: &PrintRecord,
302        job: &JobSnapshot,
303        build: bool,
304    ) -> Result<Option<PendingTurn>, CoreError> {
305        let Some(position) = position_of(print, job) else {
306            return Ok(None);
307        };
308        if build
309            && self.gcode_indexes().built(print.id).is_none()
310            && self
311                .index_owed
312                .lock()
313                .unwrap_or_else(PoisonError::into_inner)
314                .remove(&print.id)
315        {
316            // Built or not, the build is the index the next read finds.
317            let _ = self.print_gcode_index(print.id).await;
318        }
319        let Some(memo) = self.planned_memo(print.id).await? else {
320            return Ok(None);
321        };
322        if let Some(waiting) = memo.waiting {
323            let change = &waiting.reached.change;
324            if position > change.offset_bytes + crate::gcode_index::PLANNED_CHANGE_REACH_BYTES {
325                return self
326                    .resume_planned_change(print, waiting, job, position)
327                    .await;
328            }
329            return Ok(None);
330        }
331        let Some(index) = self.gcode_indexes().built(print.id) else {
332            return Ok(None);
333        };
334        let Some(change) = index.change_waiting_at(position).cloned() else {
335            self.forget_paused_at_change(print.id);
336            return Ok(None);
337        };
338        if !memo.reached.contains(&change.index)
339            && (job.state != PrinterState::Paused || self.stood_paused_at(print.id, position))
340        {
341            self.forget_paused_at_change(print.id);
342            self.reach_planned_change(
343                print,
344                &index,
345                change,
346                PlannedChangeTrigger::Position,
347                job,
348                None,
349            )
350            .await?;
351        }
352        Ok(None)
353    }
354
355    /// Whether a job read paused at a planned change has stood at this one
356    /// position for [`PAUSED_AT_CHANGE_STAND`], counting from the first such
357    /// read. A pause at the change is when `Obico`'s filament-change signal
358    /// arrives, so the signal reaches it first, and the position reaches it
359    /// alone only when no signal came, as at an `M601`.
360    fn stood_paused_at(&self, print_id: PrintId, position: u64) -> bool {
361        let now = self.clock().elapsed();
362        let mut held = self
363            .paused_at_change
364            .lock()
365            .unwrap_or_else(PoisonError::into_inner);
366        match held.get(&print_id) {
367            Some(&(at, since)) if at == position => {
368                now.saturating_sub(since) >= PAUSED_AT_CHANGE_STAND
369            }
370            _ => {
371                held.insert(print_id, (position, now));
372                false
373            }
374        }
375    }
376
377    /// Forget where a print's job stood paused at a planned change.
378    fn forget_paused_at_change(&self, print_id: PrintId) {
379        self.paused_at_change
380            .lock()
381            .unwrap_or_else(PoisonError::into_inner)
382            .remove(&print_id);
383    }
384
385    /// Whether a job stands paused at a planned change of its print's index:
386    /// reached or not, the print is a person's to change, and no check runs.
387    pub(crate) fn paused_at_planned_change(&self, print: &PrintRecord, job: &JobSnapshot) -> bool {
388        job.state == PrinterState::Paused
389            && position_of(print, job).is_some_and(|position| {
390                self.gcode_indexes()
391                    .built(print.id)
392                    .is_some_and(|index| index.change_waiting_at(position).is_some())
393            })
394    }
395
396    /// Whether a filament-change signal is one about a planned change: one
397    /// the print is already waiting at, which is answered with nothing more,
398    /// or one the job stands at now, which is recorded reached. Answers
399    /// whether it was, so a signal at no planned change is accounted as every
400    /// unplanned one is.
401    ///
402    /// # Errors
403    ///
404    /// The store's own error when what it reached could not be recorded.
405    pub(crate) async fn signal_at_planned_change(
406        &self,
407        print: &PrintRecord,
408        source_kind: &EventKind,
409    ) -> Result<bool, CoreError> {
410        if self.planned_change_waiting(print.id).await?.is_some() {
411            return Ok(true);
412        }
413        let Some(index) = self.print_gcode_index(print.id).await else {
414            return Ok(false);
415        };
416        if !plans_changes(&index) {
417            return Ok(false);
418        }
419        let Some(memo) = self.planned_memo(print.id).await? else {
420            return Ok(false);
421        };
422        let Ok(job) = self.read_job().await else {
423            return Ok(false);
424        };
425        let Some(change) = position_of(print, &job)
426            .and_then(|position| index.change_waiting_at(position))
427            .filter(|change| !memo.reached.contains(&change.index))
428            .cloned()
429        else {
430            return Ok(false);
431        };
432        self.reach_planned_change(
433            print,
434            &index,
435            change,
436            PlannedChangeTrigger::Signal,
437            &job,
438            Some(source_kind),
439        )
440        .await?;
441        Ok(true)
442    }
443
444    /// Record one planned change reached, and charge the spool feeding it up
445    /// to the change's offset.
446    async fn reach_planned_change(
447        &self,
448        print: &PrintRecord,
449        index: &GcodeIndex,
450        change: PlannedChange,
451        trigger: PlannedChangeTrigger,
452        job: &JobSnapshot,
453        signal_kind: Option<&EventKind>,
454    ) -> Result<(), CoreError> {
455        let now = self.clock().now();
456        let segments = index.planned_segments();
457        let segment = |at: u32| segments.iter().find(|segment| segment.segment == at);
458        let next = change.index + 1;
459        let next_spool_id = self
460            .stores()
461            .prints
462            .manifest(print.id)
463            .await?
464            .and_then(|manifest| {
465                manifest
466                    .segment_spools
467                    .iter()
468                    .find(|named| named.segment == next)
469                    .map(|named| named.spool_id)
470            });
471        let loaded = self.stores().filament.loaded_spools().await?;
472        let offset = i64::try_from(change.offset_bytes).unwrap_or(i64::MAX);
473        let payload = FilamentChangePlannedReachedPayload {
474            previous_color: segment(change.index).and_then(|segment| segment.color.clone()),
475            trigger,
476            position: FilePosition {
477                bytes: job.file_position_bytes.unwrap_or(offset),
478                size_bytes: job.size_bytes.filter(|size| *size > 0),
479                observed_at: now,
480            },
481            spool_id: spool_on_tool(&loaded, 0).map(|spool| spool.id),
482            next_spool_id,
483            next_segment_filament_mm: segment(next).map_or(0.0, |segment| segment.filament_mm),
484            change: change.clone(),
485        };
486        let event = self
487            .append_system_event(print.id, EventBody::of(&payload)?)
488            .await?;
489        {
490            let mut memos = self.planned_memos();
491            let memo = memos.entry(print.id).or_default();
492            memo.reached.insert(change.index);
493            memo.waiting = Some(Waiting {
494                reached: payload,
495                since: event.received_at,
496            });
497        }
498        let charged_at = FilePosition {
499            bytes: offset,
500            size_bytes: job.size_bytes.filter(|size| *size > 0),
501            observed_at: now,
502        };
503        let source_kind = signal_kind.cloned().unwrap_or_else(|| event.kind().clone());
504        self.charge_filament_change(
505            print,
506            &source_kind,
507            Whereabouts::ReadNow(charged_at),
508            Some(job.clone()),
509            Some(change.index),
510        )
511        .await
512    }
513
514    /// Record a print carried on from the change it waited at, with the
515    /// camera's frame, and claim the check that event is.
516    async fn resume_planned_change(
517        &self,
518        print: &PrintRecord,
519        waiting: Waiting,
520        job: &JobSnapshot,
521        position: u64,
522    ) -> Result<Option<PendingTurn>, CoreError> {
523        let now = self.clock().now();
524        let payload = FilamentChangePlannedResumedPayload {
525            change: waiting.reached.change.clone(),
526            previous_color: waiting.reached.previous_color.clone(),
527            waited_s: seconds_between(waiting.since, now).max(0),
528            position: FilePosition {
529                bytes: i64::try_from(position).unwrap_or(i64::MAX),
530                size_bytes: job.size_bytes.filter(|size| *size > 0),
531                observed_at: now,
532            },
533        };
534        let fetched = self.fetch_configured_frame(Some(print.id)).await;
535        let (fetched, degraded) = match fetched {
536            Some((_, Frame::Degraded(degraded))) => (None, Some(degraded)),
537            fetched => (fetched, None),
538        };
539        let event = self
540            .write_with_frame(Some(print.id), &payload, fetched)
541            .await?;
542        if let Some(degraded) = degraded {
543            self.append_system_event(print.id, EventBody::of(&degraded)?)
544                .await?;
545        }
546        if let Some(memo) = self.planned_memos().get_mut(&print.id) {
547            memo.waiting = None;
548        }
549        if let Some(images) = self.check_images.get() {
550            images.restart_growth(print.id);
551        }
552        self.checked_after_change
553            .lock()
554            .unwrap_or_else(PoisonError::into_inner)
555            .insert(print.id, self.clock().elapsed());
556        let arrival = Arrival {
557            event,
558            detection: None,
559            frame_captured_at: None,
560            camera_frame: AlertCameraFrame::NotAsked,
561        };
562        Ok(self
563            .inboxes()
564            .claim_or_hand_over(print.id, arrival.clone())
565            .then(|| PendingTurn::new(print.clone(), arrival, Vec::new())))
566    }
567
568    /// Whether a print's scheduled check is due: not until one observation
569    /// interval after the check its last planned change's resumption ran.
570    pub(crate) fn observation_due(&self, print_id: PrintId) -> bool {
571        let checked = self
572            .checked_after_change
573            .lock()
574            .unwrap_or_else(PoisonError::into_inner)
575            .get(&print_id)
576            .copied();
577        checked.is_none_or(|checked| {
578            self.clock().elapsed().saturating_sub(checked) >= self.config().observation_interval
579        })
580    }
581
582    /// How long the periodic observation should wait before its next round:
583    /// one interval, or less when a print's check after a planned change makes
584    /// its next scheduled check due sooner.
585    #[must_use]
586    pub fn until_next_observation(&self) -> Duration {
587        let interval = self.config().observation_interval;
588        let now = self.clock().elapsed();
589        self.checked_after_change
590            .lock()
591            .unwrap_or_else(PoisonError::into_inner)
592            .values()
593            .map(|checked| (*checked + interval).saturating_sub(now))
594            .filter(|left| !left.is_zero())
595            .min()
596            .map_or(interval, |left| left.min(interval))
597    }
598
599    /// Forget what this supervisor holds of a print's planned changes, once
600    /// it has closed.
601    pub(crate) fn forget_planned_changes(&self, print_id: PrintId) {
602        self.planned_memos().remove(&print_id);
603        self.index_owed
604            .lock()
605            .unwrap_or_else(PoisonError::into_inner)
606            .remove(&print_id);
607        self.checked_after_change
608            .lock()
609            .unwrap_or_else(PoisonError::into_inner)
610            .remove(&print_id);
611    }
612}