use crate::gcode_index::SlicerPlan;
use crate::records::{EffectiveBounds, Intervention, JobManifest, PrintRecord};
use crate::watch::DetectorHealth;
use printobserver_printer_api::{
HeaterSnapshot, JobError, JobSnapshot, PrinterSnapshot, PrinterState,
};
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::serde_json::Value;
use printobserver_types::{
EventId, EventKind, EventRecord, ImageRef, PrintId, Reported, Timestamp,
};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct PrintContext {
pub print: PrintRecord,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub printer: Option<PrinterSnapshot>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub job: Option<JobSnapshot>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub manifest: Option<JobManifest>,
pub bounds: EffectiveBounds,
pub interventions: Vec<Intervention>,
pub recent_events: Vec<EventRecord>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub latest_image: Option<ImageRef>,
#[serde(default)]
pub detector: DetectorHealth,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slicer: Option<SlicerPlan>,
}
impl Sample for PrintContext {
fn sample_full() -> Self {
Self {
print: PrintRecord::sample_full(),
printer: Some(PrinterSnapshot::sample_full()),
job: Some(JobSnapshot::sample_full()),
manifest: Some(JobManifest::sample_full()),
bounds: EffectiveBounds::sample_full(),
interventions: vec![Intervention::sample_full()],
recent_events: vec![EventRecord::sample_full()],
latest_image: Some(ImageRef::sample_full()),
detector: DetectorHealth::sample_full(),
slicer: Some(SlicerPlan::sample_full()),
}
}
fn sample_minimal() -> Self {
Self {
print: PrintRecord::sample_minimal(),
printer: None,
job: None,
manifest: None,
bounds: EffectiveBounds::sample_full(),
interventions: vec![],
recent_events: vec![],
latest_image: None,
detector: DetectorHealth::sample_minimal(),
slicer: None,
}
}
}
const UNREAD_PAYLOAD_FIELDS: [&str; 8] = [
"printer",
"job",
"assessment",
"interval_s",
"session_name",
"harness_identity",
"delivered",
"waited_s",
];
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentContext {
pub print: AgentPrint,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub printer: Option<AgentPrinter>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub job_error: Option<JobError>,
pub bounds: EffectiveBounds,
pub interventions: Vec<Intervention>,
pub recent_events: Vec<AgentEvent>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub latest_image: Option<ImageRef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub newest_event: Option<EventId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slicer: Option<SlicerPlan>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentPrint {
pub id: PrintId,
pub state: PrinterState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end_reason: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentPrinter {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tools: Vec<AgentHeater>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bed: Option<AgentHeater>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentHeater {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub actual_c: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target_c: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentEvent {
pub id: EventId,
pub kind: EventKind,
pub received_at: Timestamp,
#[serde(default, skip_serializing_if = "is_empty_payload")]
pub payload: Value,
}
fn is_empty_payload(payload: &Value) -> bool {
match payload {
Value::Null => true,
Value::Object(fields) => fields.is_empty(),
_ => false,
}
}
#[derive(Debug, Clone, Copy)]
pub struct Since<'events> {
pub event: EventId,
pub newer: &'events [EventRecord],
}
impl PrintContext {
#[must_use]
pub fn for_agent(&self, since: Option<Since<'_>>) -> AgentContext {
let heater = |heater: &HeaterSnapshot| AgentHeater {
actual_c: in_range(heater.actual_c.as_ref()),
target_c: in_range(heater.target_c.as_ref()),
};
let (events, newest_event) = match since {
Some(since) => (
since.newer,
Some(since.newer.first().map_or(since.event, |newest| newest.id)),
),
None => (
self.recent_events.as_slice(),
self.recent_events.first().map(|newest| newest.id),
),
};
AgentContext {
print: AgentPrint {
id: self.print.id,
state: self.print.state.clone(),
end_reason: self.print.end_reason.clone(),
},
printer: self.printer.as_ref().map(|printer| AgentPrinter {
tools: printer.tools.iter().map(heater).collect(),
bed: printer.bed.as_ref().map(heater),
}),
job_error: self.job.as_ref().and_then(|job| job.error.clone()),
bounds: self.bounds.clone(),
interventions: self.interventions.clone(),
recent_events: events.iter().map(agent_event).collect(),
latest_image: self.latest_image.clone(),
newest_event,
slicer: self.slicer.clone(),
}
}
}
#[must_use]
pub fn newer_than(events: &[EventRecord], since: EventId) -> Option<&[EventRecord]> {
events
.iter()
.position(|event| event.id == since)
.map(|at| &events[..at])
}
fn in_range(reported: Option<&Reported<f64>>) -> Option<f64> {
reported
.filter(|reported| !reported.out_of_range())
.map(Reported::value)
}
fn agent_event(event: &EventRecord) -> AgentEvent {
let mut payload = event.body.payload.clone();
if let Value::Object(fields) = &mut payload {
for unread in UNREAD_PAYLOAD_FIELDS {
fields.remove(unread);
}
}
AgentEvent {
id: event.id,
kind: event.kind().clone(),
received_at: event.received_at,
payload,
}
}
impl Sample for AgentContext {
fn sample_full() -> Self {
PrintContext::sample_full().for_agent(None)
}
fn sample_minimal() -> Self {
PrintContext::sample_minimal().for_agent(None)
}
}