1use std::time::Duration;
47
48use printobserver_printer_api::{
49 BoxFuture, PrinterErrorReason, PrinterPush, PrinterSnapshot, PrinterState,
50};
51use printobserver_types::contract::Sample;
52use printobserver_types::schemars::JsonSchema;
53use printobserver_types::serde::{Deserialize, Serialize};
54use printobserver_types::{EventKind, EventPayload as _, EventRecord, PrintId, Timestamp};
55
56use crate::error::CoreError;
57use crate::events::PendingTurn;
58use crate::inbox::Arrival;
59use crate::kinds::{
60 DetectorHealthChangedPayload, DetectorStatus, HeatedTool, PrintEndedPayload,
61 PrinterConnectionChangedPayload, PrinterResetPayload, UnattendedPrinterActivityPayload,
62 system_source,
63};
64use crate::listing::ObservedJob;
65use crate::records::{PrintOutcome, PrintRecord};
66use crate::store::HistoryQuery;
67use crate::supervisor::Supervisor;
68
69pub const DEFAULT_PRINTER_POLL: Duration = Duration::from_secs(15);
71
72pub const DEFAULT_UNATTENDED_WINDOW: Duration = Duration::from_secs(3600);
75
76pub const RESET_GRACE: Duration = Duration::from_secs(1);
84
85pub const PUSH_CHANNEL_DOWN: &str =
87 "the printer's push channel was down, so this was read from its state alone";
88
89pub const PRINTER_WATCH_KINDS: [&str; 4] = [
92 PrinterConnectionChangedPayload::KIND,
93 PrinterResetPayload::KIND,
94 UnattendedPrinterActivityPayload::KIND,
95 DetectorHealthChangedPayload::KIND,
96];
97
98#[derive(Debug, Clone, Copy, PartialEq)]
100pub struct HeadPosition {
101 pub x: f64,
103 pub y: f64,
105 pub z: f64,
107}
108
109pub trait PositionProbe: Send + Sync {
114 fn read_position(&self) -> BoxFuture<'_, Option<HeadPosition>>;
116}
117
118pub trait DetectorProbe: Send + Sync {
120 fn check(&self) -> BoxFuture<'_, Result<String, String>>;
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
127#[serde(
128 crate = "printobserver_types::serde",
129 rename_all = "snake_case",
130 deny_unknown_fields
131)]
132#[schemars(crate = "printobserver_types::schemars")]
133pub enum DetectorHealthStatus {
134 Available,
136 Unavailable,
138 #[default]
141 Unchecked,
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
152pub enum DetectorHealth {
153 #[default]
156 Unchecked,
157 Available {
159 since: Timestamp,
161 },
162 Unavailable {
164 since: Timestamp,
166 },
167}
168
169impl DetectorHealth {
170 #[must_use]
172 pub const fn status(&self) -> DetectorHealthStatus {
173 match self {
174 Self::Unchecked => DetectorHealthStatus::Unchecked,
175 Self::Available { .. } => DetectorHealthStatus::Available,
176 Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
177 }
178 }
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
184struct DetectorHealthWire {
185 status: DetectorHealthStatus,
187 #[serde(deserialize_with = "present")]
190 since: Option<Timestamp>,
191}
192
193fn present<'de, D: printobserver_types::serde::Deserializer<'de>>(
196 deserializer: D,
197) -> Result<Option<Timestamp>, D::Error> {
198 Option::deserialize(deserializer)
199}
200
201impl From<DetectorHealth> for DetectorHealthWire {
202 fn from(health: DetectorHealth) -> Self {
203 let since = match health {
204 DetectorHealth::Unchecked => None,
205 DetectorHealth::Available { since } | DetectorHealth::Unavailable { since } => {
206 Some(since)
207 }
208 };
209 Self {
210 status: health.status(),
211 since,
212 }
213 }
214}
215
216impl TryFrom<DetectorHealthWire> for DetectorHealth {
217 type Error = &'static str;
218
219 fn try_from(wire: DetectorHealthWire) -> Result<Self, Self::Error> {
220 match (wire.status, wire.since) {
221 (DetectorHealthStatus::Unchecked, None) => Ok(Self::Unchecked),
222 (DetectorHealthStatus::Available, Some(since)) => Ok(Self::Available { since }),
223 (DetectorHealthStatus::Unavailable, Some(since)) => Ok(Self::Unavailable { since }),
224 (DetectorHealthStatus::Unchecked, Some(_)) => {
225 Err("an unchecked detector has no instant it became so")
226 }
227 (_, None) => Err("a checked detector carries the instant it became so"),
228 }
229 }
230}
231
232impl Serialize for DetectorHealth {
233 fn serialize<S: printobserver_types::serde::Serializer>(
234 &self,
235 serializer: S,
236 ) -> Result<S::Ok, S::Error> {
237 DetectorHealthWire::from(*self).serialize(serializer)
238 }
239}
240
241impl<'de> Deserialize<'de> for DetectorHealth {
242 fn deserialize<D: printobserver_types::serde::Deserializer<'de>>(
243 deserializer: D,
244 ) -> Result<Self, D::Error> {
245 let wire = DetectorHealthWire::deserialize(deserializer)?;
246 Self::try_from(wire).map_err(printobserver_types::serde::de::Error::custom)
247 }
248}
249
250fn health_arm(
252 status: &str,
253 doc: &str,
254 since: &printobserver_types::serde_json::Value,
255) -> printobserver_types::serde_json::Value {
256 printobserver_types::serde_json::json!({
257 "type": "object",
258 "description": doc,
259 "properties": {
260 "status": { "type": "string", "const": status },
261 "since": since,
262 },
263 "required": ["status", "since"],
264 "additionalProperties": false,
265 })
266}
267
268impl JsonSchema for DetectorHealth {
271 fn schema_name() -> std::borrow::Cow<'static, str> {
272 std::borrow::Cow::Borrowed("DetectorHealth")
273 }
274
275 fn json_schema(
276 generator: &mut printobserver_types::schemars::SchemaGenerator,
277 ) -> printobserver_types::schemars::Schema {
278 let timestamp =
279 printobserver_types::serde_json::to_value(generator.subschema_for::<Timestamp>())
280 .unwrap_or_default();
281 let schema = printobserver_types::serde_json::json!({
282 "title": "DetectorHealth",
283 "description": "The failure detector's health, and since when it has been so: \
284 `since` is `null` exactly while the status is `unchecked`.",
285 "oneOf": [
286 health_arm(
287 "unchecked",
288 "Nothing checks it: no detector health address is configured, or no \
289 check has been made yet.",
290 &printobserver_types::serde_json::json!({
291 "type": "null",
292 "description": "Nothing: an unchecked detector has no instant it became so.",
293 }),
294 ),
295 health_arm(
296 "available",
297 "It answered its health check, from `since` on.",
298 ×tamp,
299 ),
300 health_arm(
301 "unavailable",
302 "It did not answer its health check, from `since` on.",
303 ×tamp,
304 ),
305 ],
306 });
307 printobserver_types::schemars::Schema::try_from(schema).unwrap_or_default()
308 }
309}
310
311impl Sample for DetectorHealth {
312 fn sample_full() -> Self {
313 Self::Unavailable {
314 since: Timestamp::sample_full(),
315 }
316 }
317
318 fn sample_minimal() -> Self {
319 Self::Unchecked
320 }
321
322 fn sample_alternates() -> Vec<Self> {
323 vec![Self::Available {
324 since: Timestamp::sample_full(),
325 }]
326 }
327}
328
329#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
333pub(crate) struct PushFacts {
334 pub(crate) reset: bool,
336 pub(crate) firmware_error: bool,
338 pub(crate) gap: bool,
341}
342
343#[derive(Debug, Clone, PartialEq)]
345struct Activity {
346 tools: Vec<HeatedTool>,
348 bed: Option<f64>,
350 moved: Option<bool>,
352}
353
354impl Activity {
355 fn is_active(&self) -> bool {
357 !self.tools.is_empty() || self.bed.is_some() || self.moved == Some(true)
358 }
359}
360
361#[derive(Debug, Clone)]
363struct Unattended {
364 print_id: PrintId,
366 began: Duration,
368 recorded: Option<Activity>,
370 position: Option<HeadPosition>,
372 turned_at: Option<Duration>,
375}
376
377#[derive(Debug, Default)]
379pub(crate) struct WatchState {
380 last_state: Option<PrinterState>,
382 pushes: PushFacts,
384 channel: Channel,
386 unattended: Option<Unattended>,
388 detector: DetectorHealth,
390 pending_turns: Vec<PendingTurn>,
392 pending_resets: Vec<PrinterResetPayload>,
394 pending_ends: Vec<PrintId>,
397 pending_claims: Vec<(PrintId, EventRecord)>,
400}
401
402impl WatchState {
403 const fn channel_is_down(&self) -> bool {
405 !matches!(self.channel, Channel::Open)
406 }
407}
408
409#[derive(Debug, Clone, Default, PartialEq, Eq)]
411enum Channel {
412 #[default]
414 Unknown,
415 Open,
417 Down(String),
419}
420
421#[derive(Debug, Default)]
423pub struct Watched {
424 pub turns: Vec<PendingTurn>,
427}
428
429const fn is_down(state: &PrinterState) -> bool {
431 matches!(state, PrinterState::Offline | PrinterState::Error)
432}
433
434const fn job_runs(state: &PrinterState) -> bool {
436 matches!(
437 state,
438 PrinterState::Printing | PrinterState::Paused | PrinterState::Cancelling
439 )
440}
441
442fn heated(snapshot: &PrinterSnapshot) -> (Vec<HeatedTool>, Option<f64>) {
444 let tools = snapshot
445 .tools
446 .iter()
447 .enumerate()
448 .filter_map(|(index, heater)| {
449 let target = heater.target_c.as_ref()?.value();
450 (target > 0.0).then(|| HeatedTool {
451 tool: i64::try_from(index).unwrap_or(i64::MAX),
452 target_c: target,
453 })
454 })
455 .collect();
456 let bed = snapshot
457 .bed
458 .as_ref()
459 .and_then(|bed| bed.target_c.as_ref())
460 .map(printobserver_types::Reported::value)
461 .filter(|target| *target > 0.0);
462 (tools, bed)
463}
464
465fn activity_detail(activity: &Activity, channel_down: bool) -> String {
467 let mut parts: Vec<String> = activity
468 .tools
469 .iter()
470 .map(|tool| format!("tool {} is heating to {} °C", tool.tool, tool.target_c))
471 .collect();
472 if let Some(bed) = activity.bed {
473 parts.push(format!("the bed is heating to {bed} °C"));
474 }
475 match activity.moved {
476 Some(true) => parts.push("the print head moved".to_owned()),
477 Some(false) => {}
478 None => parts.push("the print head's position could not be read".to_owned()),
479 }
480 let mut detail = format!("with no job running, {}", parts.join(", "));
481 if channel_down {
482 detail.push_str("; ");
483 detail.push_str(PUSH_CHANNEL_DOWN);
484 }
485 detail
486}
487
488impl Supervisor {
489 pub(crate) fn watch_state(&self) -> std::sync::MutexGuard<'_, WatchState> {
491 self.watch
492 .lock()
493 .unwrap_or_else(std::sync::PoisonError::into_inner)
494 }
495
496 pub(crate) fn push_facts(&self) -> PushFacts {
498 let state = self.watch_state();
499 let mut facts = state.pushes;
500 facts.gap |= state.channel_is_down();
501 facts
502 }
503
504 pub(crate) async fn pushes_after_a_reset_could_arrive(&self) -> PushFacts {
508 let started = std::time::Instant::now();
511 loop {
512 let facts = self.push_facts();
513 if facts.reset
514 || self.watch_state().channel_is_down()
515 || started.elapsed() >= RESET_GRACE
516 || crate::delay::Delay::new(Duration::from_millis(50))
517 .await
518 .is_err()
519 {
520 return facts;
521 }
522 }
523 }
524
525 pub(crate) fn note_job_running(&self) {
527 self.watch_state().unattended = None;
528 }
529
530 pub(crate) fn forget_pushes(&self) {
533 let mut state = self.watch_state();
534 let gap = state.channel_is_down();
535 state.pushes = PushFacts {
536 gap,
537 ..PushFacts::default()
538 };
539 }
540
541 #[must_use]
543 pub fn detector_health(&self) -> DetectorHealth {
544 self.watch_state().detector
545 }
546
547 pub fn note_push_channel(&self, open: Result<(), String>) {
552 let mut state = self.watch_state();
553 match open {
554 Ok(()) => state.channel = Channel::Open,
555 Err(detail) => {
556 state.channel = Channel::Down(detail);
557 state.pushes.gap = true;
558 }
559 }
560 }
561
562 pub async fn note_push(&self, push: PrinterPush) -> Result<(), CoreError> {
573 match push {
574 PrinterPush::Reset => {
575 self.distrust_z("the printer pushed a reset, and a reset forgets where Z is");
577 let running = self.running_print().await;
584 self.watch_state().pushes.reset = true;
585 let (during_print, detail) = match running {
588 Ok(Some(print)) => (
589 Some(print.id),
590 format!("the printer pushed a reset during print {}", print.id),
591 ),
592 Ok(None) => (
593 None,
594 "the printer pushed a reset while no print was running".to_owned(),
595 ),
596 Err(error) => (
597 None,
598 format!(
599 "the printer pushed a reset; which print was running could not be \
600 read: {error}"
601 ),
602 ),
603 };
604 let payload = PrinterResetPayload {
605 during_print,
606 detail,
607 };
608 if let Err(error) = self.write_reset(&payload).await {
609 self.watch_state().pending_resets.push(payload);
612 return Err(error);
613 }
614 Ok(())
615 }
616 PrinterPush::Error {
617 reason: PrinterErrorReason::Firmware,
618 } => {
619 self.watch_state().pushes.firmware_error = true;
620 Ok(())
621 }
622 PrinterPush::Error {
623 reason: PrinterErrorReason::Other(_),
624 }
625 | PrinterPush::Log { .. } => Ok(()),
626 }
627 }
628
629 async fn write_reset(&self, payload: &PrinterResetPayload) -> Result<(), CoreError> {
631 let draft = self.draft_of(None, system_source(), payload)?;
632 self.stores().events.append_event(draft).await?;
633 Ok(())
634 }
635
636 async fn catch_up(&self) {
640 let resets = std::mem::take(&mut self.watch_state().pending_resets);
641 for payload in resets {
642 if self.write_reset(&payload).await.is_err() {
643 self.watch_state().pending_resets.push(payload);
644 }
645 }
646 let ends = std::mem::take(&mut self.watch_state().pending_ends);
647 for print_id in ends {
648 if self.after_close_out(print_id).await.is_err() {
649 self.watch_state().pending_ends.push(print_id);
650 }
651 }
652 let claims = std::mem::take(&mut self.watch_state().pending_claims);
653 for (print_id, event) in claims {
654 self.claim_activity_turn(print_id, event).await;
655 }
656 }
657
658 pub(crate) async fn follow_up_end(&self, print_id: PrintId) {
661 if self.after_close_out(print_id).await.is_err() {
662 self.watch_state().pending_ends.push(print_id);
663 }
664 }
665
666 async fn running_print(&self) -> Result<Option<PrintRecord>, CoreError> {
668 Ok(self
669 .stores()
670 .prints
671 .open_prints()
672 .await?
673 .into_iter()
674 .find(|print| self.was_seen_running(print.id)))
675 }
676
677 pub async fn watch_printer(&self, probe: &dyn PositionProbe) -> Result<Watched, CoreError> {
687 self.catch_up().await;
688 let resolving = self.resolving().await;
689 let observed = self.observe_job().await;
690 if let Some(observed) = &observed {
691 self.note_connection(
692 &observed.job.state,
693 observed.job.error.as_ref().map(|error| error.text.as_str()),
694 )
695 .await?;
696 self.settle_and_adopt(observed).await?;
697 }
698 drop(resolving);
699 if let Some(observed) = &observed {
700 self.watch_unattended(observed, probe).await?;
701 }
702 Ok(Watched {
703 turns: std::mem::take(&mut self.watch_state().pending_turns),
704 })
705 }
706
707 async fn note_connection(
710 &self,
711 state: &PrinterState,
712 error: Option<&str>,
713 ) -> Result<(), CoreError> {
714 let (previous, channel_down) = {
715 let held = self.watch_state();
716 (held.last_state.clone(), held.channel_is_down())
717 };
718 if is_down(state) && previous.as_ref() != Some(state) {
719 self.distrust_z(format!(
722 "the printer went {state:?}, and Z may have moved since"
723 ));
724 }
725 let changed = previous
726 .as_ref()
727 .filter(|previous| *previous != state && (is_down(previous) || is_down(state)));
728 if let Some(previous) = changed {
729 let reporting = error
730 .filter(|error| !error.trim().is_empty())
731 .map(|error| format!(", reporting {error:?}"))
732 .unwrap_or_default();
733 let mut detail = format!("the printer went from {previous:?} to {state:?}{reporting}");
734 if channel_down {
735 detail.push_str("; ");
736 detail.push_str(PUSH_CHANNEL_DOWN);
737 }
738 let draft = self.draft_of(
739 None,
740 system_source(),
741 &PrinterConnectionChangedPayload {
742 from: previous.clone(),
743 to: state.clone(),
744 detail,
745 },
746 )?;
747 self.stores().events.append_event(draft).await?;
750 }
751 self.watch_state().last_state = Some(state.clone());
752 Ok(())
753 }
754
755 async fn after_close_out(&self, print_id: PrintId) -> Result<(), CoreError> {
759 self.forget_pushes();
760 let Some(ended) = self
761 .stores()
762 .events
763 .history(HistoryQuery {
764 print_id,
765 kinds: vec![PrintEndedPayload::kind()],
766 since: None,
767 until: None,
768 limit: Some(1),
769 })
770 .await?
771 .into_iter()
772 .next()
773 else {
774 return Ok(());
775 };
776 let Some(Ok(payload)) = ended.payload_as::<PrintEndedPayload>() else {
777 return Ok(());
778 };
779 if !matches!(
780 payload.outcome,
781 PrintOutcome::Interrupted | PrintOutcome::Failed
782 ) {
783 self.watch_state().unattended = None;
784 return Ok(());
785 }
786 self.distrust_z(format!(
787 "print {print_id} ended {}, and where it left Z is unknown",
788 if payload.outcome == PrintOutcome::Failed {
789 "failed"
790 } else {
791 "interrupted"
792 }
793 ));
794 self.watch_state().unattended = Some(Unattended {
795 print_id,
796 began: self.clock().elapsed(),
797 recorded: None,
798 position: None,
799 turned_at: None,
800 });
801 self.claim_after_end(print_id, ended).await
802 }
803
804 async fn claim_after_end(
807 &self,
808 print_id: PrintId,
809 event: EventRecord,
810 ) -> Result<(), CoreError> {
811 let Some(print) = self.stores().prints.print(print_id).await? else {
812 return Ok(());
813 };
814 let arrival = Arrival {
815 frame_captured_at: None,
816 event,
817 detection: None,
818 };
819 if self.inboxes().claim_or_hand_over(print_id, arrival.clone()) {
820 self.watch_state()
821 .pending_turns
822 .push(PendingTurn::new(print, arrival, Vec::new()));
823 }
824 Ok(())
825 }
826
827 async fn watch_unattended(
830 &self,
831 observed: &ObservedJob,
832 probe: &dyn PositionProbe,
833 ) -> Result<(), CoreError> {
834 let window = self.config().unattended_window;
835 let now = self.clock().elapsed();
836 let (print_id, last_position, channel_down) = {
837 let mut held = self.watch_state();
838 let Some(open) = &held.unattended else {
839 return Ok(());
840 };
841 if now.saturating_sub(open.began) > window {
842 held.unattended = None;
843 return Ok(());
844 }
845 (open.print_id, open.position, held.channel_is_down())
846 };
847 if job_runs(&observed.job.state) || is_down(&observed.job.state) {
848 return Ok(());
849 }
850 let Ok(snapshot) = self.read_snapshot().await else {
851 return Ok(());
852 };
853 if job_runs(&snapshot.connection) || is_down(&snapshot.connection) {
854 return Ok(());
855 }
856 let (tools, bed) = heated(&snapshot);
857 let position = probe.read_position().await;
858 let moved = match (last_position, position) {
859 (_, None) => None,
860 (None, Some(_)) => Some(false),
861 (Some(before), Some(after)) => Some(before != after),
862 };
863 let activity = Activity { tools, bed, moved };
864 let unchanged = {
865 let mut held = self.watch_state();
866 let Some(open) = held
867 .unattended
868 .as_mut()
869 .filter(|open| open.print_id == print_id)
870 else {
871 return Ok(());
872 };
873 if position.is_some() {
874 open.position = position;
875 }
876 if !activity.is_active() {
877 open.recorded = None;
878 return Ok(());
879 }
880 open.recorded.as_ref() == Some(&activity)
881 };
882 if unchanged {
883 return Ok(());
884 }
885 let draft = self.draft_of(
886 None,
887 system_source(),
888 &UnattendedPrinterActivityPayload {
889 last_print_id: print_id,
890 tools: activity.tools.clone(),
891 bed_target_c: activity.bed,
892 moved: activity.moved,
893 detail: activity_detail(&activity, channel_down),
894 },
895 )?;
896 let event = self.stores().events.append_event(draft).await?;
897 let interval = self.config().observation_interval;
898 let turn_due = {
899 let mut held = self.watch_state();
900 let Some(open) = held.unattended.as_mut() else {
901 return Ok(());
902 };
903 open.recorded = Some(activity.clone());
906 open.turned_at
907 .is_none_or(|turned| now.saturating_sub(turned) >= interval)
908 };
909 if turn_due {
910 self.claim_activity_turn(print_id, event).await;
911 }
912 Ok(())
913 }
914
915 async fn claim_activity_turn(&self, print_id: PrintId, event: EventRecord) {
919 if self.claim_after_end(print_id, event.clone()).await.is_err() {
920 self.watch_state().pending_claims.push((print_id, event));
921 return;
922 }
923 let now = self.clock().elapsed();
924 if let Some(open) = self
925 .watch_state()
926 .unattended
927 .as_mut()
928 .filter(|open| open.print_id == print_id)
929 {
930 open.turned_at = Some(now);
931 }
932 }
933
934 pub async fn check_detector(
945 &self,
946 probe: &dyn DetectorProbe,
947 ) -> Result<Option<PendingTurn>, CoreError> {
948 let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
949 return Ok(None);
950 };
951 let (status, detail) = match probe.check().await {
952 Ok(detail) => (DetectorStatus::Available, detail),
953 Err(detail) => (DetectorStatus::Unavailable, detail),
954 };
955 let health = match status {
956 DetectorStatus::Available => DetectorHealthStatus::Available,
957 DetectorStatus::Unavailable => DetectorHealthStatus::Unavailable,
958 };
959 let previous = self.watch_state().detector.status();
960 if previous == health {
961 return Ok(None);
962 }
963 let since = self.clock().now();
964 let found = match status {
965 DetectorStatus::Available => DetectorHealth::Available { since },
966 DetectorStatus::Unavailable => DetectorHealth::Unavailable { since },
967 };
968 if previous == DetectorHealthStatus::Unchecked && health == DetectorHealthStatus::Available
971 {
972 self.watch_state().detector = found;
973 return Ok(None);
974 }
975 let draft = self.draft_of(
976 None,
977 system_source(),
978 &DetectorHealthChangedPayload { status, detail },
979 )?;
980 let event = self.stores().events.append_event(draft).await?;
981 self.watch_state().detector = found;
984 if status != DetectorStatus::Unavailable {
985 return Ok(None);
986 }
987 let arrival = Arrival {
988 frame_captured_at: None,
989 event,
990 detection: None,
991 };
992 Ok(self
993 .inboxes()
994 .claim_or_hand_over(print.id, arrival.clone())
995 .then(|| PendingTurn::new(print, arrival, Vec::new())))
996 }
997}
998
999pub(crate) fn concerns_its_end(kind: &EventKind) -> bool {
1002 [
1003 PrintEndedPayload::KIND,
1004 UnattendedPrinterActivityPayload::KIND,
1005 ]
1006 .contains(&kind.as_str())
1007}
1008
1009pub(crate) fn noticed_of(event: &EventRecord) -> Option<String> {
1012 if let Some(Ok(ended)) = event.payload_as::<PrintEndedPayload>() {
1013 let outcome = match ended.outcome {
1014 PrintOutcome::Interrupted => "interrupted",
1015 PrintOutcome::Failed => "failed",
1016 PrintOutcome::Completed | PrintOutcome::Cancelled => return None,
1017 };
1018 return Some(format!(
1019 "{}: the print ended {outcome}, the printer reporting {:?} ({})",
1020 PrintEndedPayload::KIND,
1021 ended.state,
1022 ended.reason
1023 ));
1024 }
1025 if let Some(Ok(activity)) = event.payload_as::<UnattendedPrinterActivityPayload>() {
1026 return Some(format!(
1027 "{}: after print {} ended, {}",
1028 UnattendedPrinterActivityPayload::KIND,
1029 activity.last_print_id,
1030 activity.detail
1031 ));
1032 }
1033 if let Some(Ok(degraded)) = event.payload_as::<crate::kinds::CameraDegradedPayload>() {
1034 return Some(format!(
1035 "{}: the camera gave no usable frame in {} attempts, so there is no frame to look \
1036 at: {}",
1037 crate::kinds::CameraDegradedPayload::KIND,
1038 degraded.attempts,
1039 degraded.detail
1040 ));
1041 }
1042 if let Some(Ok(health)) = event.payload_as::<DetectorHealthChangedPayload>() {
1043 return Some(format!(
1044 "{}: the failure detector is {:?}, so nothing is watching the print for failures: {}",
1045 DetectorHealthChangedPayload::KIND,
1046 health.status,
1047 health.detail
1048 ));
1049 }
1050 None
1051}