1use crate::gcode_index::SlicerPlan;
19use crate::records::{EffectiveBounds, Intervention, JobManifest, PrintRecord};
20use crate::watch::DetectorHealth;
21use printobserver_printer_api::{
22 HeaterSnapshot, JobError, JobSnapshot, PrinterSnapshot, PrinterState,
23};
24use printobserver_types::contract::Sample;
25use printobserver_types::schemars::JsonSchema;
26use printobserver_types::serde::{Deserialize, Serialize};
27use printobserver_types::serde_json::Value;
28use printobserver_types::{
29 EventId, EventKind, EventRecord, ImageRef, PrintId, Reported, Timestamp,
30};
31
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
34#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
35#[schemars(crate = "printobserver_types::schemars")]
36pub struct PrintContext {
37 pub print: PrintRecord,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub printer: Option<PrinterSnapshot>,
42 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub job: Option<JobSnapshot>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub manifest: Option<JobManifest>,
48 pub bounds: EffectiveBounds,
50 pub interventions: Vec<Intervention>,
52 pub recent_events: Vec<EventRecord>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub latest_image: Option<ImageRef>,
57 #[serde(default)]
59 pub detector: DetectorHealth,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
64 pub slicer: Option<SlicerPlan>,
65}
66
67impl Sample for PrintContext {
68 fn sample_full() -> Self {
69 Self {
70 print: PrintRecord::sample_full(),
71 printer: Some(PrinterSnapshot::sample_full()),
72 job: Some(JobSnapshot::sample_full()),
73 manifest: Some(JobManifest::sample_full()),
74 bounds: EffectiveBounds::sample_full(),
75 interventions: vec![Intervention::sample_full()],
76 recent_events: vec![EventRecord::sample_full()],
77 latest_image: Some(ImageRef::sample_full()),
78 detector: DetectorHealth::sample_full(),
79 slicer: Some(SlicerPlan::sample_full()),
80 }
81 }
82
83 fn sample_minimal() -> Self {
84 Self {
85 print: PrintRecord::sample_minimal(),
86 printer: None,
87 job: None,
88 manifest: None,
89 bounds: EffectiveBounds::sample_full(),
90 interventions: vec![],
91 recent_events: vec![],
92 latest_image: None,
93 detector: DetectorHealth::sample_minimal(),
94 slicer: None,
95 }
96 }
97}
98
99const UNREAD_PAYLOAD_FIELDS: [&str; 8] = [
104 "printer",
105 "job",
106 "assessment",
107 "interval_s",
108 "session_name",
109 "harness_identity",
110 "delivered",
111 "waited_s",
112];
113
114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
132#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
133#[schemars(crate = "printobserver_types::schemars")]
134pub struct AgentContext {
135 pub print: AgentPrint,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub printer: Option<AgentPrinter>,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
142 pub job_error: Option<JobError>,
143 pub bounds: EffectiveBounds,
145 pub interventions: Vec<Intervention>,
147 pub recent_events: Vec<AgentEvent>,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub latest_image: Option<ImageRef>,
154 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub newest_event: Option<EventId>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub slicer: Option<SlicerPlan>,
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
165#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
166#[schemars(crate = "printobserver_types::schemars")]
167pub struct AgentPrint {
168 pub id: PrintId,
170 pub state: PrinterState,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub end_reason: Option<String>,
175}
176
177#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
179#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
180#[schemars(crate = "printobserver_types::schemars")]
181pub struct AgentPrinter {
182 #[serde(default, skip_serializing_if = "Vec::is_empty")]
184 pub tools: Vec<AgentHeater>,
185 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub bed: Option<AgentHeater>,
188}
189
190#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
193#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
194#[schemars(crate = "printobserver_types::schemars")]
195pub struct AgentHeater {
196 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub actual_c: Option<f64>,
199 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub target_c: Option<f64>,
202}
203
204#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
207#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
208#[schemars(crate = "printobserver_types::schemars")]
209pub struct AgentEvent {
210 pub id: EventId,
212 pub kind: EventKind,
214 pub received_at: Timestamp,
216 #[serde(default, skip_serializing_if = "is_empty_payload")]
219 pub payload: Value,
220}
221
222fn is_empty_payload(payload: &Value) -> bool {
224 match payload {
225 Value::Null => true,
226 Value::Object(fields) => fields.is_empty(),
227 _ => false,
228 }
229}
230
231#[derive(Debug, Clone, Copy)]
234pub struct Since<'events> {
235 pub event: EventId,
237 pub newer: &'events [EventRecord],
239}
240
241impl PrintContext {
242 #[must_use]
245 pub fn for_agent(&self, since: Option<Since<'_>>) -> AgentContext {
246 let heater = |heater: &HeaterSnapshot| AgentHeater {
247 actual_c: in_range(heater.actual_c.as_ref()),
248 target_c: in_range(heater.target_c.as_ref()),
249 };
250 let (events, newest_event) = match since {
251 Some(since) => (
252 since.newer,
253 Some(since.newer.first().map_or(since.event, |newest| newest.id)),
254 ),
255 None => (
256 self.recent_events.as_slice(),
257 self.recent_events.first().map(|newest| newest.id),
258 ),
259 };
260 AgentContext {
261 print: AgentPrint {
262 id: self.print.id,
263 state: self.print.state.clone(),
264 end_reason: self.print.end_reason.clone(),
265 },
266 printer: self.printer.as_ref().map(|printer| AgentPrinter {
267 tools: printer.tools.iter().map(heater).collect(),
268 bed: printer.bed.as_ref().map(heater),
269 }),
270 job_error: self.job.as_ref().and_then(|job| job.error.clone()),
271 bounds: self.bounds.clone(),
272 interventions: self.interventions.clone(),
273 recent_events: events.iter().map(agent_event).collect(),
274 latest_image: self.latest_image.clone(),
275 newest_event,
276 slicer: self.slicer.clone(),
277 }
278 }
279}
280
281#[must_use]
284pub fn newer_than(events: &[EventRecord], since: EventId) -> Option<&[EventRecord]> {
285 events
286 .iter()
287 .position(|event| event.id == since)
288 .map(|at| &events[..at])
289}
290
291fn in_range(reported: Option<&Reported<f64>>) -> Option<f64> {
293 reported
294 .filter(|reported| !reported.out_of_range())
295 .map(Reported::value)
296}
297
298fn agent_event(event: &EventRecord) -> AgentEvent {
300 let mut payload = event.body.payload.clone();
301 if let Value::Object(fields) = &mut payload {
302 for unread in UNREAD_PAYLOAD_FIELDS {
303 fields.remove(unread);
304 }
305 }
306 AgentEvent {
307 id: event.id,
308 kind: event.kind().clone(),
309 received_at: event.received_at,
310 payload,
311 }
312}
313
314impl Sample for AgentContext {
315 fn sample_full() -> Self {
316 PrintContext::sample_full().for_agent(None)
317 }
318
319 fn sample_minimal() -> Self {
320 PrintContext::sample_minimal().for_agent(None)
321 }
322}