use std::time::Duration;
use printobserver_printer_api::{
BoxFuture, PrinterErrorReason, PrinterPush, PrinterSnapshot, PrinterState,
};
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{EventKind, EventPayload as _, EventRecord, PrintId, Timestamp};
use crate::error::CoreError;
use crate::events::PendingTurn;
use crate::inbox::Arrival;
use crate::kinds::{
DetectorHealthChangedPayload, DetectorStatus, HeatedTool, PortFailureSite, PrintEndedPayload,
PrinterConnectionChangedPayload, PrinterResetPayload, UnattendedPrinterActivityPayload,
system_source,
};
use crate::listing::ObservedJob;
use crate::records::{PrintOutcome, PrintRecord};
use crate::store::HistoryQuery;
use crate::supervisor::Supervisor;
pub const DEFAULT_PRINTER_POLL: Duration = Duration::from_secs(15);
pub const DEFAULT_UNATTENDED_WINDOW: Duration = Duration::from_secs(3600);
pub const RESET_GRACE: Duration = Duration::from_secs(1);
pub const PUSH_CHANNEL_DOWN: &str =
"the printer's push channel was down, so this was read from its state alone";
pub const PRINTER_WATCH_KINDS: [&str; 4] = [
PrinterConnectionChangedPayload::KIND,
PrinterResetPayload::KIND,
UnattendedPrinterActivityPayload::KIND,
DetectorHealthChangedPayload::KIND,
];
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HeadPosition {
pub x: f64,
pub y: f64,
pub z: f64,
}
pub trait PositionProbe: Send + Sync {
fn read_position(&self) -> BoxFuture<'_, Option<HeadPosition>>;
}
pub trait DetectorProbe: Send + Sync {
fn check(&self) -> BoxFuture<'_, Result<String, String>>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(
crate = "printobserver_types::serde",
rename_all = "snake_case",
deny_unknown_fields
)]
#[schemars(crate = "printobserver_types::schemars")]
pub enum DetectorHealthStatus {
ScoringNothingFlagged,
ScoringFlagged,
Available,
Unavailable,
#[default]
Unchecked,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DetectorHealth {
Unchecked {
scoring_unread: Option<String>,
},
Available {
since: Timestamp,
scoring_unread: Option<String>,
},
Unavailable {
since: Timestamp,
scoring_unread: Option<String>,
},
Scoring {
since: Timestamp,
verdict: ScoringVerdict,
probe_failure: Option<String>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScoringVerdict {
NothingFlagged,
Flagged,
}
impl Default for DetectorHealth {
fn default() -> Self {
Self::Unchecked {
scoring_unread: None,
}
}
}
impl DetectorHealth {
#[must_use]
pub const fn status(&self) -> DetectorHealthStatus {
match self {
Self::Unchecked { .. } => DetectorHealthStatus::Unchecked,
Self::Available { .. } => DetectorHealthStatus::Available,
Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
Self::Scoring {
verdict: ScoringVerdict::NothingFlagged,
..
} => DetectorHealthStatus::ScoringNothingFlagged,
Self::Scoring {
verdict: ScoringVerdict::Flagged,
..
} => DetectorHealthStatus::ScoringFlagged,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
struct DetectorHealthWire {
status: DetectorHealthStatus,
#[serde(deserialize_with = "present")]
since: Option<Timestamp>,
#[serde(default, skip_serializing_if = "Option::is_none")]
probe_failure: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
scoring_unread: Option<String>,
}
fn present<'de, D: printobserver_types::serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Option<Timestamp>, D::Error> {
Option::deserialize(deserializer)
}
impl From<DetectorHealth> for DetectorHealthWire {
fn from(health: DetectorHealth) -> Self {
let status = health.status();
let (since, probe_failure, scoring_unread) = match health {
DetectorHealth::Unchecked { scoring_unread } => (None, None, scoring_unread),
DetectorHealth::Available {
since,
scoring_unread,
}
| DetectorHealth::Unavailable {
since,
scoring_unread,
} => (Some(since), None, scoring_unread),
DetectorHealth::Scoring {
since,
probe_failure,
..
} => (Some(since), probe_failure, None),
};
Self {
status,
since,
probe_failure,
scoring_unread,
}
}
}
impl TryFrom<DetectorHealthWire> for DetectorHealth {
type Error = &'static str;
fn try_from(wire: DetectorHealthWire) -> Result<Self, Self::Error> {
let DetectorHealthWire {
status,
since,
probe_failure,
scoring_unread,
} = wire;
let scoring = matches!(
status,
DetectorHealthStatus::ScoringNothingFlagged | DetectorHealthStatus::ScoringFlagged
);
if scoring && scoring_unread.is_some() {
return Err("a scoring detector's scoring is being read");
}
if !scoring && probe_failure.is_some() {
return Err("only a scoring detector names its failing health check beside it");
}
match (status, since) {
(DetectorHealthStatus::Unchecked, None) => Ok(Self::Unchecked { scoring_unread }),
(DetectorHealthStatus::Available, Some(since)) => Ok(Self::Available {
since,
scoring_unread,
}),
(DetectorHealthStatus::Unavailable, Some(since)) => Ok(Self::Unavailable {
since,
scoring_unread,
}),
(DetectorHealthStatus::ScoringNothingFlagged, Some(since)) => Ok(Self::Scoring {
since,
verdict: ScoringVerdict::NothingFlagged,
probe_failure,
}),
(DetectorHealthStatus::ScoringFlagged, Some(since)) => Ok(Self::Scoring {
since,
verdict: ScoringVerdict::Flagged,
probe_failure,
}),
(DetectorHealthStatus::Unchecked, Some(_)) => {
Err("an unchecked detector has no instant it became so")
}
(_, None) => Err("a checked detector carries the instant it became so"),
}
}
}
impl Serialize for DetectorHealth {
fn serialize<S: printobserver_types::serde::Serializer>(
&self,
serializer: S,
) -> Result<S::Ok, S::Error> {
DetectorHealthWire::from(self.clone()).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for DetectorHealth {
fn deserialize<D: printobserver_types::serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Self, D::Error> {
let wire = DetectorHealthWire::deserialize(deserializer)?;
Self::try_from(wire).map_err(printobserver_types::serde::de::Error::custom)
}
}
fn health_arm(
status: &str,
doc: &str,
since: &printobserver_types::serde_json::Value,
beside: (&str, &str),
) -> printobserver_types::serde_json::Value {
let (field, field_doc) = beside;
let mut properties = printobserver_types::serde_json::Map::new();
properties.insert(
"status".to_owned(),
printobserver_types::serde_json::json!({ "type": "string", "const": status }),
);
properties.insert("since".to_owned(), since.clone());
properties.insert(
field.to_owned(),
printobserver_types::serde_json::json!({ "type": "string", "description": field_doc }),
);
printobserver_types::serde_json::json!({
"type": "object",
"description": doc,
"properties": properties,
"required": ["status", "since"],
"additionalProperties": false,
})
}
const SCORING_UNREAD_DOC: &str = "Why the detector's scoring of the print is not being read, \
when it is not: no Obico API is configured, no Obico printer is known yet, or the last read \
failed.";
const PROBE_FAILURE_DOC: &str = "What the detector's health check answered, when it is \
failing while the detector scores the print.";
impl JsonSchema for DetectorHealth {
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("DetectorHealth")
}
fn json_schema(
generator: &mut printobserver_types::schemars::SchemaGenerator,
) -> printobserver_types::schemars::Schema {
let timestamp =
printobserver_types::serde_json::to_value(generator.subschema_for::<Timestamp>())
.unwrap_or_default();
let unread = ("scoring_unread", SCORING_UNREAD_DOC);
let failing = ("probe_failure", PROBE_FAILURE_DOC);
let schema = printobserver_types::serde_json::json!({
"title": "DetectorHealth",
"description": "The failure detector's status, and since when it has been so: \
`since` is `null` exactly while the status is `unchecked`. Evidence that the \
detector is scoring the print comes before its health check.",
"oneOf": [
health_arm(
"scoring_nothing_flagged",
"The detector is scoring the print, from `since` on, and no failure alert \
of its own has arrived for it.",
×tamp,
failing,
),
health_arm(
"scoring_flagged",
"The detector is scoring the print, from `since` on, and a failure alert \
of its own has arrived for it.",
×tamp,
failing,
),
health_arm(
"available",
"No evidence that the detector is scoring the print, and it answered its \
health check, from `since` on: available, with no scores yet.",
×tamp,
unread,
),
health_arm(
"unavailable",
"No evidence that the detector is scoring the print, and it did not answer \
its health check, from `since` on.",
×tamp,
unread,
),
health_arm(
"unchecked",
"No evidence of any kind: no detector health address is configured, or no \
check has been made yet, and nothing shows the detector scoring.",
&printobserver_types::serde_json::json!({
"type": "null",
"description": "Nothing: an unchecked detector has no instant it became so.",
}),
unread,
),
],
});
printobserver_types::schemars::Schema::try_from(schema).unwrap_or_default()
}
}
impl Sample for DetectorHealth {
fn sample_full() -> Self {
Self::Scoring {
since: Timestamp::sample_full(),
verdict: ScoringVerdict::NothingFlagged,
probe_failure: Some("the detector's health check answered 503".to_owned()),
}
}
fn sample_minimal() -> Self {
Self::Unchecked {
scoring_unread: None,
}
}
fn sample_alternates() -> Vec<Self> {
vec![
Self::Scoring {
since: Timestamp::sample_full(),
verdict: ScoringVerdict::Flagged,
probe_failure: None,
},
Self::Available {
since: Timestamp::sample_full(),
scoring_unread: Some(
"no Obico printer is known yet: no [obico] printer_id is configured and Obico \
has posted nothing naming one since this server started"
.to_owned(),
),
},
Self::Unavailable {
since: Timestamp::sample_full(),
scoring_unread: None,
},
Self::Unchecked {
scoring_unread: Some(
"no [obico] url and access_token are configured, so Obico's record of the \
print is not read"
.to_owned(),
),
},
]
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) enum ProbeHealth {
#[default]
Unchecked,
Available {
since: Timestamp,
},
Unavailable {
since: Timestamp,
detail: String,
},
}
impl ProbeHealth {
const fn status(&self) -> DetectorHealthStatus {
match self {
Self::Unchecked => DetectorHealthStatus::Unchecked,
Self::Available { .. } => DetectorHealthStatus::Available,
Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct PushFacts {
pub(crate) reset: bool,
pub(crate) firmware_error: bool,
pub(crate) gap: bool,
}
#[derive(Debug, Clone, PartialEq)]
struct Activity {
tools: Vec<HeatedTool>,
bed: Option<f64>,
moved: Option<bool>,
}
impl Activity {
fn is_active(&self) -> bool {
!self.tools.is_empty() || self.bed.is_some() || self.moved == Some(true)
}
}
#[derive(Debug, Clone)]
struct Unattended {
print_id: PrintId,
began: Duration,
recorded: Option<Activity>,
position: Option<HeadPosition>,
turned_at: Option<Duration>,
}
#[derive(Debug, Default)]
pub(crate) struct WatchState {
last_state: Option<PrinterState>,
pushes: PushFacts,
channel: Channel,
unattended: Option<Unattended>,
pub(crate) probe: ProbeHealth,
pub(crate) scoring: crate::scoring::ScoringState,
pending_turns: Vec<PendingTurn>,
pending_resets: Vec<PrinterResetPayload>,
pending_ends: Vec<PrintId>,
pending_claims: Vec<(PrintId, EventRecord)>,
}
impl WatchState {
const fn channel_is_down(&self) -> bool {
!matches!(self.channel, Channel::Open)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
enum Channel {
#[default]
Unknown,
Open,
Down(String),
}
#[derive(Debug, Default)]
pub struct Watched {
pub turns: Vec<PendingTurn>,
pub active: Option<ActiveJob>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ActiveJob {
pub print_id: PrintId,
pub file_position_bytes: Option<i64>,
}
const fn is_down(state: &PrinterState) -> bool {
matches!(state, PrinterState::Offline | PrinterState::Error)
}
const fn job_runs(state: &PrinterState) -> bool {
matches!(
state,
PrinterState::Printing | PrinterState::Paused | PrinterState::Cancelling
)
}
fn heated(snapshot: &PrinterSnapshot) -> (Vec<HeatedTool>, Option<f64>) {
let tools = snapshot
.tools
.iter()
.enumerate()
.filter_map(|(index, heater)| {
let target = heater.target_c.as_ref()?.value();
(target > 0.0).then(|| HeatedTool {
tool: i64::try_from(index).unwrap_or(i64::MAX),
target_c: target,
})
})
.collect();
let bed = snapshot
.bed
.as_ref()
.and_then(|bed| bed.target_c.as_ref())
.map(printobserver_types::Reported::value)
.filter(|target| *target > 0.0);
(tools, bed)
}
fn activity_detail(activity: &Activity, channel_down: bool) -> String {
let mut parts: Vec<String> = activity
.tools
.iter()
.map(|tool| format!("tool {} is heating to {} °C", tool.tool, tool.target_c))
.collect();
if let Some(bed) = activity.bed {
parts.push(format!("the bed is heating to {bed} °C"));
}
match activity.moved {
Some(true) => parts.push("the print head moved".to_owned()),
Some(false) => {}
None => parts.push("the print head's position could not be read".to_owned()),
}
let mut detail = format!("with no job running, {}", parts.join(", "));
if channel_down {
detail.push_str("; ");
detail.push_str(PUSH_CHANNEL_DOWN);
}
detail
}
impl Supervisor {
pub(crate) fn watch_state(&self) -> std::sync::MutexGuard<'_, WatchState> {
self.watch
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) fn push_facts(&self) -> PushFacts {
let state = self.watch_state();
let mut facts = state.pushes;
facts.gap |= state.channel_is_down();
facts
}
pub(crate) async fn pushes_after_a_reset_could_arrive(&self) -> PushFacts {
let started = std::time::Instant::now();
loop {
let facts = self.push_facts();
if facts.reset
|| self.watch_state().channel_is_down()
|| started.elapsed() >= RESET_GRACE
|| crate::delay::Delay::new(Duration::from_millis(50))
.await
.is_err()
{
return facts;
}
}
}
pub(crate) fn note_job_running(&self) {
self.watch_state().unattended = None;
}
pub(crate) fn forget_pushes(&self) {
let mut state = self.watch_state();
let gap = state.channel_is_down();
state.pushes = PushFacts {
gap,
..PushFacts::default()
};
}
#[must_use]
pub fn detector_health(&self) -> DetectorHealth {
self.detector_health_of(None)
}
#[must_use]
pub fn detector_health_for(&self, print_id: PrintId) -> DetectorHealth {
self.detector_health_of(Some(print_id))
}
fn detector_health_of(&self, print_id: Option<PrintId>) -> DetectorHealth {
let window = self
.config()
.observation_interval
.saturating_mul(crate::scoring::EVIDENCE_INTERVALS);
let now = self.clock().elapsed();
let held = self.watch_state();
if let Some(scoring) = held.scoring.scoring(print_id, now, window) {
return DetectorHealth::Scoring {
since: scoring.since,
verdict: scoring.verdict,
probe_failure: match &held.probe {
ProbeHealth::Unavailable { detail, .. } => Some(detail.clone()),
ProbeHealth::Unchecked | ProbeHealth::Available { .. } => None,
},
};
}
let scoring_unread = held.scoring.unread().map(str::to_owned);
match &held.probe {
ProbeHealth::Unchecked => DetectorHealth::Unchecked { scoring_unread },
ProbeHealth::Available { since } => DetectorHealth::Available {
since: *since,
scoring_unread,
},
ProbeHealth::Unavailable { since, .. } => DetectorHealth::Unavailable {
since: *since,
scoring_unread,
},
}
}
pub fn note_push_channel(&self, open: Result<(), String>) {
let mut state = self.watch_state();
match open {
Ok(()) => state.channel = Channel::Open,
Err(detail) => {
state.channel = Channel::Down(detail);
state.pushes.gap = true;
}
}
}
pub async fn note_push(&self, push: PrinterPush) -> Result<(), CoreError> {
match push {
PrinterPush::Reset => {
self.distrust_z("the printer pushed a reset, and a reset forgets where Z is");
let running = self.running_print().await;
self.watch_state().pushes.reset = true;
let (during_print, detail) = match running {
Ok(Some(print)) => (
Some(print.id),
format!("the printer pushed a reset during print {}", print.id),
),
Ok(None) => (
None,
"the printer pushed a reset while no print was running".to_owned(),
),
Err(error) => (
None,
format!(
"the printer pushed a reset; which print was running could not be \
read: {error}"
),
),
};
let payload = PrinterResetPayload {
during_print,
detail,
};
if let Err(error) = self.write_reset(&payload).await {
self.watch_state().pending_resets.push(payload);
return Err(error);
}
Ok(())
}
PrinterPush::Error {
reason: PrinterErrorReason::Firmware,
} => {
self.watch_state().pushes.firmware_error = true;
Ok(())
}
PrinterPush::Error {
reason: PrinterErrorReason::Other(_),
}
| PrinterPush::Log { .. } => Ok(()),
}
}
async fn write_reset(&self, payload: &PrinterResetPayload) -> Result<(), CoreError> {
let draft = self.draft_of(None, system_source(), payload)?;
self.stores().events.append_event(draft).await?;
Ok(())
}
async fn catch_up(&self) {
let resets = std::mem::take(&mut self.watch_state().pending_resets);
for payload in resets {
if self.write_reset(&payload).await.is_err() {
self.watch_state().pending_resets.push(payload);
}
}
let ends = std::mem::take(&mut self.watch_state().pending_ends);
for print_id in ends {
if self.after_close_out(print_id).await.is_err() {
self.watch_state().pending_ends.push(print_id);
}
}
let claims = std::mem::take(&mut self.watch_state().pending_claims);
for (print_id, event) in claims {
self.claim_activity_turn(print_id, event).await;
}
}
pub(crate) async fn follow_up_end(&self, print_id: PrintId) {
if self.after_close_out(print_id).await.is_err() {
self.watch_state().pending_ends.push(print_id);
}
}
async fn running_print(&self) -> Result<Option<PrintRecord>, CoreError> {
Ok(self
.stores()
.prints
.open_prints()
.await?
.into_iter()
.find(|print| self.was_seen_running(print.id)))
}
pub async fn watch_printer(&self, probe: &dyn PositionProbe) -> Result<Watched, CoreError> {
self.catch_up().await;
let resolving = self.resolving().await;
let observed = self.observe_job().await;
let mut active = None;
if let Some(observed) = &observed {
self.note_connection(
&observed.job.state,
observed.job.error.as_ref().map(|error| error.text.as_str()),
)
.await?;
active = self
.settle_and_adopt(observed)
.await?
.map(|print_id| ActiveJob {
print_id,
file_position_bytes: observed.job.file_position_bytes,
});
}
drop(resolving);
if let Some(observed) = &observed {
self.watch_unattended(observed, probe).await?;
if let Some(active) = &active
&& let Some(print) = self.stores().prints.print(active.print_id).await?
&& let Some(turn) = self
.follow_planned_changes(&print, &observed.job, true)
.await?
{
self.watch_state().pending_turns.push(turn);
}
}
Ok(Watched {
turns: std::mem::take(&mut self.watch_state().pending_turns),
active,
})
}
async fn note_connection(
&self,
state: &PrinterState,
error: Option<&str>,
) -> Result<(), CoreError> {
let (previous, channel_down) = {
let held = self.watch_state();
(held.last_state.clone(), held.channel_is_down())
};
if is_down(state) && previous.as_ref() != Some(state) {
self.distrust_z(format!(
"the printer went {state:?}, and Z may have moved since"
));
}
let changed = previous
.as_ref()
.filter(|previous| *previous != state && (is_down(previous) || is_down(state)));
if let Some(previous) = changed {
let reporting = error
.filter(|error| !error.trim().is_empty())
.map(|error| format!(", reporting {error:?}"))
.unwrap_or_default();
let mut detail = format!("the printer went from {previous:?} to {state:?}{reporting}");
if channel_down {
detail.push_str("; ");
detail.push_str(PUSH_CHANNEL_DOWN);
}
let draft = self.draft_of(
None,
system_source(),
&PrinterConnectionChangedPayload {
from: previous.clone(),
to: state.clone(),
detail,
},
)?;
self.stores().events.append_event(draft).await?;
}
self.watch_state().last_state = Some(state.clone());
Ok(())
}
async fn after_close_out(&self, print_id: PrintId) -> Result<(), CoreError> {
self.forget_pushes();
let Some(ended) = self
.stores()
.events
.history(HistoryQuery {
print_id,
kinds: vec![PrintEndedPayload::kind()],
since: None,
until: None,
limit: Some(1),
})
.await?
.into_iter()
.next()
else {
return Ok(());
};
let Some(Ok(payload)) = ended.payload_as::<PrintEndedPayload>() else {
return Ok(());
};
if !matches!(
payload.outcome,
PrintOutcome::Interrupted | PrintOutcome::Failed
) {
self.watch_state().unattended = None;
return Ok(());
}
self.distrust_z(format!(
"print {print_id} ended {}, and where it left Z is unknown",
if payload.outcome == PrintOutcome::Failed {
"failed"
} else {
"interrupted"
}
));
self.watch_state().unattended = Some(Unattended {
print_id,
began: self.clock().elapsed(),
recorded: None,
position: None,
turned_at: None,
});
self.claim_after_end(print_id, ended).await
}
async fn claim_after_end(
&self,
print_id: PrintId,
event: EventRecord,
) -> Result<(), CoreError> {
let Some(print) = self.stores().prints.print(print_id).await? else {
return Ok(());
};
let arrival = Arrival {
frame_captured_at: None,
event,
detection: None,
camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
};
if self.inboxes().claim_or_hand_over(print_id, arrival.clone()) {
self.watch_state()
.pending_turns
.push(PendingTurn::new(print, arrival, Vec::new()));
}
Ok(())
}
async fn watch_unattended(
&self,
observed: &ObservedJob,
probe: &dyn PositionProbe,
) -> Result<(), CoreError> {
let window = self.config().unattended_window;
let now = self.clock().elapsed();
let (print_id, last_position, channel_down) = {
let mut held = self.watch_state();
let Some(open) = &held.unattended else {
return Ok(());
};
if now.saturating_sub(open.began) > window {
held.unattended = None;
return Ok(());
}
(open.print_id, open.position, held.channel_is_down())
};
if job_runs(&observed.job.state) || is_down(&observed.job.state) {
return Ok(());
}
let Ok(snapshot) = self.read_snapshot().await else {
return Ok(());
};
if job_runs(&snapshot.connection) || is_down(&snapshot.connection) {
return Ok(());
}
let (tools, bed) = heated(&snapshot);
let position = probe.read_position().await;
let moved = match (last_position, position) {
(_, None) => None,
(None, Some(_)) => Some(false),
(Some(before), Some(after)) => Some(before != after),
};
let activity = Activity { tools, bed, moved };
let unchanged = {
let mut held = self.watch_state();
let Some(open) = held
.unattended
.as_mut()
.filter(|open| open.print_id == print_id)
else {
return Ok(());
};
if position.is_some() {
open.position = position;
}
if !activity.is_active() {
open.recorded = None;
return Ok(());
}
open.recorded.as_ref() == Some(&activity)
};
if unchanged {
return Ok(());
}
let draft = self.draft_of(
None,
system_source(),
&UnattendedPrinterActivityPayload {
last_print_id: print_id,
tools: activity.tools.clone(),
bed_target_c: activity.bed,
moved: activity.moved,
detail: activity_detail(&activity, channel_down),
},
)?;
let event = self.stores().events.append_event(draft).await?;
let interval = self.config().observation_interval;
let turn_due = {
let mut held = self.watch_state();
let Some(open) = held.unattended.as_mut() else {
return Ok(());
};
open.recorded = Some(activity.clone());
open.turned_at
.is_none_or(|turned| now.saturating_sub(turned) >= interval)
};
if turn_due {
self.claim_activity_turn(print_id, event).await;
}
Ok(())
}
async fn claim_activity_turn(&self, print_id: PrintId, event: EventRecord) {
if self.claim_after_end(print_id, event.clone()).await.is_err() {
self.watch_state().pending_claims.push((print_id, event));
return;
}
let now = self.clock().elapsed();
if let Some(open) = self
.watch_state()
.unattended
.as_mut()
.filter(|open| open.print_id == print_id)
{
open.turned_at = Some(now);
}
}
pub async fn check_detector(
&self,
probe: &dyn DetectorProbe,
) -> Result<Option<PendingTurn>, CoreError> {
let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
return Ok(None);
};
let (status, detail) = match probe.check().await {
Ok(detail) => (DetectorStatus::Available, detail),
Err(detail) => (DetectorStatus::Unavailable, detail),
};
let health = match status {
DetectorStatus::Available => DetectorHealthStatus::Available,
DetectorStatus::Unavailable => DetectorHealthStatus::Unavailable,
};
let previous = self.watch_state().probe.status();
if previous == health {
if let ProbeHealth::Unavailable { detail: held, .. } = &mut self.watch_state().probe {
held.clone_from(&detail);
}
return Ok(None);
}
let since = self.clock().now();
let found = match status {
DetectorStatus::Available => ProbeHealth::Available { since },
DetectorStatus::Unavailable => ProbeHealth::Unavailable {
since,
detail: detail.clone(),
},
};
if previous == DetectorHealthStatus::Unchecked && health == DetectorHealthStatus::Available
{
self.watch_state().probe = found;
return Ok(None);
}
let draft = self.draft_of(
None,
system_source(),
&DetectorHealthChangedPayload {
status,
detail: detail.clone(),
},
)?;
let event = self.stores().events.append_event(draft).await?;
self.watch_state().probe = found;
if status != DetectorStatus::Unavailable {
return Ok(None);
}
if matches!(
self.detector_health_for(print.id),
DetectorHealth::Scoring { .. }
) {
self.record_port_failure_to(
None,
event.id,
PortFailureSite::DetectorHealthCheck,
detail,
)
.await;
return Ok(None);
}
if !self.turns_allowed(print.id).await? {
return Ok(None);
}
let arrival = Arrival {
frame_captured_at: None,
event,
detection: None,
camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
};
Ok(self
.inboxes()
.claim_or_hand_over(print.id, arrival.clone())
.then(|| PendingTurn::new(print, arrival, Vec::new())))
}
}
pub(crate) fn concerns_its_end(kind: &EventKind) -> bool {
[
PrintEndedPayload::KIND,
UnattendedPrinterActivityPayload::KIND,
]
.contains(&kind.as_str())
}
fn resumed_noticed(resumed: &crate::kinds::FilamentChangePlannedResumedPayload) -> String {
let named = |colour: Option<&str>| {
colour.map_or_else(
|| "a colour the file does not name".to_owned(),
str::to_owned,
)
};
let change = &resumed.change;
let what = match change.kind {
crate::gcode_index::PlannedChangeKind::ColorChange => "colour change",
crate::gcode_index::PlannedChangeKind::Pause => "pause",
};
format!(
"{}: the print carried on from planned {what} {} after waiting {} s; the expected colour \
is {} from layer {} (Z {} mm) up, and the colour before it was {}",
crate::kinds::FilamentChangePlannedResumedPayload::KIND,
change.index,
resumed.waited_s,
named(change.color.as_deref()),
change.layer,
change.z_mm,
named(resumed.previous_color.as_deref()),
)
}
pub(crate) fn noticed_of(event: &EventRecord) -> Option<String> {
if let Some(Ok(ended)) = event.payload_as::<PrintEndedPayload>() {
let outcome = match ended.outcome {
PrintOutcome::Interrupted => "interrupted",
PrintOutcome::Failed => "failed",
PrintOutcome::Completed | PrintOutcome::Cancelled => return None,
};
return Some(format!(
"{}: the print ended {outcome}, the printer reporting {:?} ({})",
PrintEndedPayload::KIND,
ended.state,
ended.reason
));
}
if let Some(Ok(activity)) = event.payload_as::<UnattendedPrinterActivityPayload>() {
return Some(format!(
"{}: after print {} ended, {}",
UnattendedPrinterActivityPayload::KIND,
activity.last_print_id,
activity.detail
));
}
if let Some(Ok(degraded)) = event.payload_as::<crate::kinds::CameraDegradedPayload>() {
return Some(format!(
"{}: the camera gave no usable frame in {} attempts, so there is no frame to look \
at: {}",
crate::kinds::CameraDegradedPayload::KIND,
degraded.attempts,
degraded.detail
));
}
if let Some(Ok(resumed)) =
event.payload_as::<crate::kinds::FilamentChangePlannedResumedPayload>()
{
return Some(resumed_noticed(&resumed));
}
if let Some(Ok(health)) = event.payload_as::<DetectorHealthChangedPayload>() {
return Some(format!(
"{}: the failure detector is {:?}, so nothing is watching the print for failures: {}",
DetectorHealthChangedPayload::KIND,
health.status,
health.detail
));
}
None
}