1use core::future::Future;
80use core::ops::ControlFlow;
81use core::pin::Pin;
82use core::task::{Context, Poll, Waker};
83use std::collections::BTreeMap;
84use std::sync::{Arc, Mutex, PoisonError};
85
86use printobserver_printer_api::GcodeSink;
87use printobserver_types::contract::Sample;
88use printobserver_types::schemars::JsonSchema;
89use printobserver_types::serde::{Deserialize, Serialize};
90use printobserver_types::{PrintId, Timestamp};
91
92use crate::toolpath::{
93 ChangeFact, ExtrusionKind, LayerFacts, LayerRef, LayerToolpath, ObjectOutline, Reach,
94 SpoolError, ToolpathSegment,
95};
96
97const LINE_LIMIT: usize = 4096;
102
103const TYPE_LIMIT: usize = 64;
106
107const RISE_WINDOW_S: i64 = 30 * 60;
110
111const LAYERS_SHOWN_BELOW: usize = 5;
114
115const FLOW_WELL_UNDER_ONE: f64 = 0.9;
117
118const OVER_AIR: [&str; 2] = ["Bridge infill", "Overhang perimeter"];
120
121const SUPPORTS: [&str; 2] = ["Support material", "Support material interface"];
123
124const WALLS: [&str; 2] = ["Perimeter", "External perimeter"];
126
127const OBJECT_LIMIT: usize = 1024;
129
130const AXIS_LIMIT: f64 = 1e4;
133
134const WORD_LIMIT: f64 = 1e7;
137
138const WORD_COUNT: usize = 8;
140
141const TRAVEL_MM: f64 = 1e-6;
143
144const NOT_THE_PART: &str = "Custom";
146
147const FAN_FULL: f64 = 255.0;
149
150const CHORD_MM: f64 = 0.5;
152
153pub const PLANNED_CHANGE_REACH_BYTES: u64 = 4096;
162
163const CHANGE_LIMIT: usize = 1024;
166
167#[derive(Debug, Clone, Copy, PartialEq)]
170struct Head {
171 at: [f64; 3],
173 e: f64,
175 axes: Positioning,
177 extruder: Positioning,
179 current_type: Option<usize>,
181 width_mm: f32,
183}
184
185#[derive(Debug, Clone, PartialEq)]
187struct Layer {
188 begins: u64,
190 at: u64,
192 head: Head,
194 z_mm: Option<f64>,
196 types: u64,
199}
200
201#[derive(Debug, Clone, Copy, PartialEq)]
203struct Mark<T> {
204 at: u64,
206 value: T,
208}
209
210#[derive(Debug, Clone, Default, PartialEq)]
212struct ObjectDraft {
213 bounds: Option<[f64; 4]>,
215 reach: Reach,
217}
218
219#[derive(Debug, Clone, PartialEq)]
221pub struct GcodeIndex {
222 bytes: u64,
224 lines: u64,
226 layers: Vec<Layer>,
228 type_names: Vec<String>,
230 labelled_types: bool,
232 time_left: Vec<Mark<i64>>,
234 flow: Vec<Mark<f64>>,
236 fan: Vec<Mark<f64>>,
238 objects: Vec<BedArea>,
240 labelled_objects: bool,
242 outlines: Vec<ObjectOutline>,
245 blocks: Vec<(u64, Option<usize>)>,
248 spool: Option<std::path::PathBuf>,
250 changes: Vec<ChangeMark>,
252 change_minutes: Vec<Mark<i64>>,
254 first_colour: Option<String>,
256 extruded_mm: f64,
258}
259
260#[derive(Debug, Clone, PartialEq)]
262struct ChangeMark {
263 change: PlannedChange,
265 at: u64,
267 fed_before_mm: f64,
269}
270
271#[derive(Debug, Clone, Copy, PartialEq)]
274pub struct SetInFile {
275 pub value: f64,
277 pub at: u64,
279}
280
281impl GcodeIndex {
282 #[must_use]
284 pub const fn bytes(&self) -> u64 {
285 self.bytes
286 }
287
288 #[must_use]
290 pub const fn lines(&self) -> u64 {
291 self.lines
292 }
293
294 #[must_use]
296 pub const fn layer_count(&self) -> usize {
297 self.layers.len()
298 }
299
300 #[must_use]
303 pub const fn entries(&self) -> usize {
304 self.layers.len()
305 + self.time_left.len()
306 + self.flow.len()
307 + self.fan.len()
308 + self.objects.len()
309 + self.changes.len()
310 + self.change_minutes.len()
311 }
312
313 #[must_use]
316 pub fn resident_bytes(&self) -> usize {
317 let names: usize = self.type_names.iter().map(String::capacity).sum();
318 core::mem::size_of::<Self>()
319 + self.layers.capacity() * core::mem::size_of::<Layer>()
320 + self.type_names.capacity() * core::mem::size_of::<String>()
321 + names
322 + self.time_left.capacity() * core::mem::size_of::<Mark<i64>>()
323 + self.flow.capacity() * core::mem::size_of::<Mark<f64>>()
324 + self.fan.capacity() * core::mem::size_of::<Mark<f64>>()
325 + self.objects.capacity() * core::mem::size_of::<BedArea>()
326 + self.outlines.capacity() * core::mem::size_of::<ObjectOutline>()
327 + self
328 .outlines
329 .iter()
330 .map(|outline| outline.hull_mm.capacity() * core::mem::size_of::<[f32; 2]>())
331 .sum::<usize>()
332 + self.blocks.capacity() * core::mem::size_of::<(u64, Option<usize>)>()
333 + self.changes.capacity() * core::mem::size_of::<ChangeMark>()
334 + self
335 .changes
336 .iter()
337 .filter_map(|mark| mark.change.color.as_ref())
338 .map(String::capacity)
339 .sum::<usize>()
340 + self.change_minutes.capacity() * core::mem::size_of::<Mark<i64>>()
341 + self.first_colour.as_ref().map_or(0, String::capacity)
342 }
343
344 #[must_use]
347 pub fn planned_changes(&self) -> Vec<PlannedChange> {
348 self.changes
349 .iter()
350 .map(|mark| mark.change.clone())
351 .collect()
352 }
353
354 #[must_use]
356 pub fn planned_change(&self, index: u32) -> Option<&PlannedChange> {
357 self.changes
358 .iter()
359 .map(|mark| &mark.change)
360 .find(|change| change.index == index)
361 }
362
363 #[must_use]
366 pub fn planned_segments(&self) -> Vec<PlannedSegment> {
367 if self.changes.is_empty() {
368 return Vec::new();
369 }
370 let colours = core::iter::once(&self.first_colour)
373 .chain(self.changes.iter().map(|mark| &mark.change.color));
374 let fed = core::iter::once(0.0)
375 .chain(self.changes.iter().map(|mark| mark.fed_before_mm))
376 .zip(
377 self.changes
378 .iter()
379 .map(|mark| mark.fed_before_mm)
380 .chain(core::iter::once(self.extruded_mm)),
381 );
382 let segments: Vec<PlannedSegment> = (0_u32..)
383 .zip(colours.zip(fed))
384 .map(|(segment, (colour, (from, to)))| PlannedSegment {
385 segment,
386 color: colour.clone(),
387 filament_mm: millimetres(to - from),
388 })
389 .collect();
390 segments
391 }
392
393 #[must_use]
397 pub fn change_waiting_at(&self, file_position_bytes: u64) -> Option<&PlannedChange> {
398 self.changes
399 .iter()
400 .rev()
401 .map(|mark| &mark.change)
402 .find(|change| change.offset_bytes <= file_position_bytes)
403 .filter(|change| waits_at(change, file_position_bytes))
404 }
405
406 fn changes_read(&self, position: i64) -> usize {
408 u64::try_from(position).map_or(0, |position| {
409 self.changes.partition_point(|mark| mark.at <= position)
410 })
411 }
412
413 #[must_use]
418 pub fn expected_color_at(&self, position: i64) -> Option<String> {
419 if self.changes.is_empty() {
420 return None;
421 }
422 match self.changes_read(position).checked_sub(1) {
423 None => self.first_colour.clone(),
424 Some(last) => self.changes[last].change.color.clone(),
425 }
426 }
427
428 #[must_use]
432 pub fn object_outlines(&self) -> &[ObjectOutline] {
433 &self.outlines
434 }
435
436 #[must_use]
441 pub fn object_at(&self, file_position_bytes: u64) -> Option<usize> {
442 if !self.labelled_objects {
443 return (!self.outlines.is_empty()).then_some(0);
444 }
445 let started = self
446 .blocks
447 .partition_point(|(start, _)| *start <= file_position_bytes);
448 self.blocks[..started]
449 .iter()
450 .rev()
451 .find_map(|(_, outline)| *outline)
452 }
453
454 #[must_use]
456 pub fn layer_at(&self, file_position_bytes: u64) -> Option<LayerRef> {
457 self.layers
458 .iter()
459 .rposition(|layer| layer.at <= file_position_bytes)
460 .map(LayerRef)
461 }
462
463 #[must_use]
465 pub fn layer_z_mm(&self, layer: LayerRef) -> Option<f64> {
466 self.layers.get(layer.0).and_then(|held| held.z_mm)
467 }
468
469 fn lays_object(&self, layer: &Layer) -> bool {
474 layer.types & !self.type_bits(&SUPPORTS) != 0
475 }
476
477 #[must_use]
480 pub fn object_layer_at_or_below(&self, layer: LayerRef) -> Option<LayerRef> {
481 let held = self.layers.get(..=layer.0)?;
482 held.iter()
483 .rposition(|layer| self.lays_object(layer))
484 .map(LayerRef)
485 }
486
487 #[must_use]
490 pub fn first_object_layer(&self) -> Option<(LayerRef, u64)> {
491 let first = self
492 .layers
493 .iter()
494 .position(|layer| self.lays_object(layer))?;
495 Some((LayerRef(first), self.layer_end(first)))
496 }
497
498 fn layer_end(&self, index: usize) -> u64 {
500 self.layers
501 .get(index + 1)
502 .map_or(self.bytes, |next| next.begins)
503 }
504
505 pub fn layer_toolpath(&self, layer: LayerRef) -> Result<LayerToolpath, SpoolError> {
514 use std::io::{Read as _, Seek as _, SeekFrom};
515
516 let held = self.layers.get(layer.0).ok_or(SpoolError::UnknownLayer)?;
517 let path = self.spool.as_ref().ok_or(SpoolError::NoSpool)?;
518 let io = |error: std::io::Error| SpoolError::Io {
519 detail: error.to_string(),
520 };
521 let length =
522 usize::try_from(self.layer_end(layer.0).saturating_sub(held.at)).map_err(|_| {
523 SpoolError::Io {
524 detail: "a layer too long to hold".to_owned(),
525 }
526 })?;
527 let mut file = std::fs::File::open(path).map_err(io)?;
528 file.seek(SeekFrom::Start(held.at)).map_err(io)?;
529 let mut bytes = vec![0; length];
530 file.read_exact(&mut bytes).map_err(io)?;
531 let mut builder = IndexBuilder::reading_layer(self.type_names.clone(), held.head, held.at);
532 let _ = builder.take(&bytes);
533 if !builder.line.is_empty() {
534 builder.end_line();
535 }
536 #[expect(
537 clippy::cast_possible_truncation,
538 reason = "a layer height is a few hundred millimetres at most"
539 )]
540 let z_mm = held.z_mm.unwrap_or(0.0) as f32;
541 Ok(LayerToolpath {
542 z_mm,
543 segments: builder.collected.unwrap_or_default(),
544 })
545 }
546
547 pub fn planned_head_at(
557 &self,
558 file_position_bytes: u64,
559 ) -> Result<Option<[f64; 2]>, SpoolError> {
560 Ok(self
561 .planned_heads_before(file_position_bytes, 0)?
562 .map(|trail| trail.last))
563 }
564
565 pub fn planned_heads_before(
577 &self,
578 file_position_bytes: u64,
579 moves: usize,
580 ) -> Result<Option<PlannedHeads>, SpoolError> {
581 use std::io::{Read as _, Seek as _, SeekFrom};
582
583 let Some(layer) = self.layer_at(file_position_bytes) else {
584 return Ok(None);
585 };
586 let held = &self.layers[layer.0];
587 let path = self.spool.as_ref().ok_or(SpoolError::NoSpool)?;
588 let io = |error: std::io::Error| SpoolError::Io {
589 detail: error.to_string(),
590 };
591 let end = file_position_bytes.min(self.layer_end(layer.0));
592 let length = usize::try_from(end.saturating_sub(held.at)).map_err(|_| SpoolError::Io {
593 detail: "a layer too long to hold".to_owned(),
594 })?;
595 let mut file = std::fs::File::open(path).map_err(io)?;
596 file.seek(SeekFrom::Start(held.at)).map_err(io)?;
597 let mut bytes = vec![0; length];
598 file.read_exact(&mut bytes).map_err(io)?;
599 let mut builder = IndexBuilder::reading_layer(self.type_names.clone(), held.head, held.at);
600 builder.trail = Some(vec![[held.head.at[0], held.head.at[1]]]);
601 let _ = builder.take(&bytes);
604 let [x, y, _] = builder.at;
605 let mut trail = builder.trail.unwrap_or_default();
606 let keep = trail.len().saturating_sub(moves.saturating_add(1));
607 trail.drain(..keep);
608 Ok(Some(PlannedHeads {
609 last: [x, y],
610 trail,
611 }))
612 }
613
614 #[must_use]
618 pub fn busiest_layer(&self) -> Option<(usize, i64)> {
619 self.layers
620 .iter()
621 .map(|layer| {
622 (
623 usize::try_from(layer.types.count_ones()).unwrap_or(usize::MAX),
624 i64::try_from(layer.at).unwrap_or(i64::MAX),
625 )
626 })
627 .reduce(|best, next| if next.0 > best.0 { next } else { best })
628 }
629
630 #[must_use]
634 pub fn layer_facts(
635 &self,
636 file_position_bytes: u64,
637 toolpath: &LayerToolpath,
638 ) -> Option<LayerFacts> {
639 let layer = self.layer_at(file_position_bytes)?;
640 let number = layer.0 + 1;
641 let position = i64::try_from(file_position_bytes).unwrap_or(i64::MAX);
642 let expected_colour = self.expected_color_at(position);
646 let fact = |mark: &ChangeMark, just_made: bool| ChangeFact {
647 just_made,
648 number: mark.change.index.saturating_add(1),
649 colour_change: mark.change.kind == PlannedChangeKind::ColorChange,
650 layer: mark.change.layer,
651 z_mm: mark.change.z_mm,
652 colour: mark.change.color.clone(),
653 };
654 let read = self.changes_read(position);
655 let just_made = read
656 .checked_sub(1)
657 .map(|last| &self.changes[last])
658 .filter(|mark| usize::try_from(mark.change.layer).ok() == Some(number))
659 .map(|mark| fact(mark, true));
660 let change = just_made.or_else(|| self.changes.get(read).map(|mark| fact(mark, false)));
661 Some(LayerFacts {
662 number,
663 count: self.layers.len(),
664 z_mm: self
665 .layer_z_mm(layer)
666 .unwrap_or_else(|| f64::from(toolpath.z_mm)),
667 expected_colour,
668 change,
669 progress: toolpath.progress(file_position_bytes),
670 })
671 }
672
673 #[must_use]
675 pub fn flow_at(&self, position: i64) -> Option<SetInFile> {
676 last_at(&self.flow, position).map(|mark| SetInFile {
677 value: mark.value,
678 at: mark.at,
679 })
680 }
681
682 #[must_use]
685 pub fn fan_at(&self, position: i64) -> Option<SetInFile> {
686 last_at(&self.fan, position).map(|mark| SetInFile {
687 value: mark.value,
688 at: mark.at,
689 })
690 }
691
692 #[must_use]
695 pub fn plan_at(&self, position: i64) -> SlicerPlan {
696 self.plan_with(position, None, None)
697 }
698
699 #[must_use]
703 pub fn plan_with(
704 &self,
705 position: i64,
706 flow_changed: Option<f64>,
707 fan_changed: Option<f64>,
708 ) -> SlicerPlan {
709 let mut unknown = Vec::new();
710 let layer_index = self
711 .layers
712 .iter()
713 .rposition(|layer| reached(layer.at, position));
714 let final_z_mm = self.layers.last().and_then(|layer| layer.z_mm);
715 if self.layers.is_empty() {
716 unknown.push(PlanFact::Layer);
717 }
718 if final_z_mm.is_none() {
719 unknown.push(PlanFact::FinalZ);
720 }
721 if !self.labelled_types {
722 unknown.push(PlanFact::Types);
723 }
724 let types = layer_index.map_or_else(Vec::new, |index| {
725 let bits = self.layers[index].types;
726 self.type_names
727 .iter()
728 .enumerate()
729 .filter(|(bit, _)| bits & (1 << bit) != 0)
730 .map(|(_, name)| name.clone())
731 .collect()
732 });
733 let minutes_left = last_at(&self.time_left, position).map(|mark| mark.value);
734 if minutes_left.is_none() {
735 unknown.push(PlanFact::MinutesLeft);
736 }
737 let flow_factor = set_value(
738 self.flow_at(position).map(|set| set.value),
739 flow_changed,
740 PlanFact::FlowFactor,
741 &mut unknown,
742 );
743 let fan_percent = set_value(
744 self.fan_at(position).map(|set| set.value),
745 fan_changed,
746 PlanFact::FanPercent,
747 &mut unknown,
748 );
749 if !self.labelled_objects {
750 unknown.push(PlanFact::Objects);
751 }
752 unknown.sort_unstable();
753 let in_force =
754 |set: &Option<SetValue>| set.as_ref().and_then(|set| set.changed.or(set.file));
755 let mut at_odds = Vec::new();
756 if let Some(index) = layer_index {
757 let shown = self.layers[index.saturating_sub(LAYERS_SHOWN_BELOW)..=index]
758 .iter()
759 .fold(0, |bits, layer| bits | layer.types);
760 if in_force(&fan_percent).is_some_and(|fan| fan <= 0.0)
761 && shown & self.type_bits(&OVER_AIR) != 0
762 {
763 at_odds.push(PlanMismatch::FanOffOverBridges);
764 }
765 if in_force(&flow_factor).is_some_and(|flow| flow < FLOW_WELL_UNDER_ONE)
766 && self.layers[index].types & self.type_bits(&WALLS) != 0
767 {
768 at_odds.push(PlanMismatch::FlowLowOverWalls);
769 }
770 }
771 let next_change = self
772 .changes
773 .get(self.changes_read(position))
774 .map(|mark| mark.change.clone());
775 let minutes_to_next_change = next_change
776 .as_ref()
777 .and_then(|_| last_at(&self.change_minutes, position))
778 .map(|mark| mark.value);
779 SlicerPlan {
780 expected_color: self.expected_color_at(position),
781 next_change,
782 minutes_to_next_change,
783 change_waiting: None,
784 layer: layer_index.map(|index| index + 1),
785 z_mm: layer_index.and_then(|index| self.layers[index].z_mm),
786 final_z_mm,
787 types,
788 minutes_left,
789 flow_factor,
790 fan_percent,
791 object_count: self.labelled_objects.then_some(self.objects.len()),
792 objects: self.objects.clone(),
793 rise: None,
794 at_odds,
795 unknown,
796 }
797 }
798
799 fn type_bits(&self, names: &[&str]) -> u64 {
801 self.type_names
802 .iter()
803 .enumerate()
804 .filter(|(_, name)| names.contains(&name.as_str()))
805 .fold(0, |bits, (bit, _)| bits | (1 << bit))
806 }
807
808 #[must_use]
817 pub fn risen_since(&self, earlier: i64, now: i64) -> Option<f64> {
818 self.height_and_rise_since(earlier, now)
819 .map(|[_, risen]| risen)
820 }
821
822 #[must_use]
826 pub fn height_and_rise_since(&self, earlier: i64, now: i64) -> Option<[f64; 2]> {
827 let at = |position| {
828 self.layers
829 .iter()
830 .rposition(|layer| reached(layer.at, position))
831 .filter(|index| self.layers[*index].z_mm.is_some())
832 };
833 let (then, now) = (at(earlier)?, at(now)?);
834 let supports = self.type_bits(&SUPPORTS);
835 let lays_the_part = |layer: &&Layer| layer.types & !supports != 0;
836 let mut top = self.layers[..=then]
839 .iter()
840 .rev()
841 .filter(lays_the_part)
842 .find_map(|layer| layer.z_mm)
843 .or(self.layers[then].z_mm)?;
844 let height = top;
845 let mut risen = 0.0;
846 for layer in self
847 .layers
848 .iter()
849 .take(now + 1)
850 .skip(then + 1)
851 .filter(lays_the_part)
852 {
853 let Some(z) = layer.z_mm else { continue };
854 risen += (z - top).max(0.0);
855 top = top.max(z);
856 }
857 let tenth = |mm: f64| (mm * 10.0).round() / 10.0;
858 Some([tenth(height), tenth(risen)])
859 }
860}
861
862fn set_value(
865 file: Option<f64>,
866 changed: Option<f64>,
867 fact: PlanFact,
868 unknown: &mut Vec<PlanFact>,
869) -> Option<SetValue> {
870 if file.is_none() {
871 unknown.push(fact);
872 }
873 (file.is_some() || changed.is_some()).then_some(SetValue { file, changed })
874}
875
876const fn waits_at(change: &PlannedChange, position: u64) -> bool {
878 position >= change.offset_bytes && position - change.offset_bytes <= PLANNED_CHANGE_REACH_BYTES
879}
880
881fn millimetres(length: f64) -> f64 {
883 (length.max(0.0) * 1000.0).round() / 1000.0
884}
885
886fn reached(at: u64, position: i64) -> bool {
888 u64::try_from(position).is_ok_and(|position| at <= position)
889}
890
891fn last_at<T: Copy>(marks: &[Mark<T>], position: i64) -> Option<Mark<T>> {
893 let Ok(position) = u64::try_from(position) else {
894 return None;
895 };
896 let reached = marks.partition_point(|mark| mark.at <= position);
897 reached.checked_sub(1).map(|index| marks[index])
898}
899
900#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
903#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
904#[schemars(crate = "printobserver_types::schemars")]
905pub struct SetValue {
906 #[serde(default, skip_serializing_if = "Option::is_none")]
908 pub file: Option<f64>,
909 #[serde(default, skip_serializing_if = "Option::is_none")]
912 pub changed: Option<f64>,
913}
914
915pub type BedArea = [i64; 4];
920
921#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
924#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
925#[schemars(crate = "printobserver_types::schemars")]
926pub struct Rise {
927 pub since: Timestamp,
932 pub mm: [f64; 2],
938}
939
940pub(crate) fn null_is_sent(schema: &mut printobserver_types::schemars::Schema) {
948 use printobserver_types::serde_json::Value;
949 if let Some(Value::Object(properties)) = schema.get_mut("properties") {
950 for property in properties.values_mut() {
951 if property.get("properties").is_some()
952 && let Ok(inline) =
953 printobserver_types::schemars::Schema::try_from(core::mem::take(property))
954 {
955 let mut inline = inline;
956 null_is_sent(&mut inline);
957 *property = inline.to_value();
958 }
959 }
960 }
961 let nullable = |property: &Value| match property.get("type") {
962 Some(Value::Array(types)) => types.iter().any(|named| named == "null"),
963 _ => property
964 .get("anyOf")
965 .and_then(Value::as_array)
966 .is_some_and(|arms| {
967 arms.iter()
968 .any(|arm| arm.get("type") == Some(&Value::from("null")))
969 }),
970 };
971 let sent: Vec<Value> = schema
972 .get("properties")
973 .and_then(Value::as_object)
974 .map(|properties| {
975 properties
976 .iter()
977 .filter(|(_, property)| nullable(property))
978 .map(|(name, _)| Value::from(name.as_str()))
979 .collect()
980 })
981 .unwrap_or_default();
982 if sent.is_empty() {
983 return;
984 }
985 let required = schema
986 .ensure_object()
987 .entry("required")
988 .or_insert_with(|| Value::Array(Vec::new()));
989 if let Value::Array(required) = required {
990 for name in sent {
991 if !required.contains(&name) {
992 required.push(name);
993 }
994 }
995 }
996}
997
998#[derive(Debug, Clone, PartialEq)]
1000pub struct PlannedHeads {
1001 pub last: [f64; 2],
1003 pub trail: Vec<[f64; 2]>,
1006}
1007
1008#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1010#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1011#[schemars(crate = "printobserver_types::schemars")]
1012pub enum PlannedChangeKind {
1013 ColorChange,
1015 Pause,
1017}
1018
1019#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1022#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1023#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
1024pub struct PlannedChange {
1025 pub index: u32,
1027 pub kind: PlannedChangeKind,
1029 pub offset_bytes: u64,
1031 pub layer: u32,
1034 pub z_mm: f64,
1036 pub color: Option<String>,
1040}
1041
1042#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1044#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1045#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
1046pub struct PlannedSegment {
1047 pub segment: u32,
1050 pub color: Option<String>,
1053 pub filament_mm: f64,
1055}
1056
1057#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1059#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1060#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
1061pub struct PlannedChanges {
1062 pub changes: Vec<PlannedChange>,
1064 pub segments: Vec<PlannedSegment>,
1066 pub waiting: Option<u32>,
1069 pub expected_color: Option<String>,
1072}
1073
1074impl Sample for PlannedChange {
1075 fn sample_full() -> Self {
1076 Self {
1077 index: 0,
1078 kind: PlannedChangeKind::ColorChange,
1079 offset_bytes: 48_213,
1080 layer: 12,
1081 z_mm: 2.4,
1082 color: Some("#FF0000".to_owned()),
1083 }
1084 }
1085
1086 fn sample_alternates() -> Vec<Self> {
1087 vec![Self {
1088 index: 1,
1089 kind: PlannedChangeKind::Pause,
1090 offset_bytes: 96_410,
1091 layer: 24,
1092 z_mm: 4.8,
1093 color: None,
1094 }]
1095 }
1096}
1097
1098impl Sample for PlannedSegment {
1099 fn sample_full() -> Self {
1100 Self {
1101 segment: 1,
1102 color: Some("#FF0000".to_owned()),
1103 filament_mm: 812.4,
1104 }
1105 }
1106
1107 fn sample_alternates() -> Vec<Self> {
1108 vec![Self {
1109 segment: 0,
1110 color: None,
1111 filament_mm: 0.0,
1112 }]
1113 }
1114}
1115
1116impl Sample for PlannedChanges {
1117 fn sample_full() -> Self {
1118 Self {
1119 changes: vec![PlannedChange::sample_full()],
1120 segments: vec![
1121 PlannedSegment {
1122 segment: 0,
1123 color: Some("#FFFFFF".to_owned()),
1124 filament_mm: 301.7,
1125 },
1126 PlannedSegment::sample_full(),
1127 ],
1128 waiting: Some(0),
1129 expected_color: Some("#FF0000".to_owned()),
1130 }
1131 }
1132
1133 fn sample_alternates() -> Vec<Self> {
1134 vec![Self {
1135 waiting: None,
1136 expected_color: None,
1137 ..Self::sample_full()
1138 }]
1139 }
1140}
1141
1142#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1145#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1146#[schemars(crate = "printobserver_types::schemars")]
1147pub enum PlanMismatch {
1148 FanOffOverBridges,
1151 FlowLowOverWalls,
1153}
1154
1155#[derive(
1157 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
1158)]
1159#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1160#[schemars(crate = "printobserver_types::schemars")]
1161pub enum PlanFact {
1162 Layer,
1164 FinalZ,
1166 Types,
1168 MinutesLeft,
1170 FlowFactor,
1172 FanPercent,
1174 Objects,
1176 Rise,
1180}
1181
1182#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1189#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1190#[schemars(crate = "printobserver_types::schemars")]
1191pub struct SlicerPlan {
1192 #[serde(default, skip_serializing_if = "Option::is_none")]
1196 pub expected_color: Option<String>,
1197 #[serde(default, skip_serializing_if = "Option::is_none")]
1200 pub next_change: Option<PlannedChange>,
1201 #[serde(default, skip_serializing_if = "Option::is_none")]
1205 pub minutes_to_next_change: Option<i64>,
1206 #[serde(default, skip_serializing_if = "Option::is_none")]
1209 pub change_waiting: Option<PlannedChange>,
1210 #[serde(default, skip_serializing_if = "Option::is_none")]
1213 pub layer: Option<usize>,
1214 #[serde(default, skip_serializing_if = "Option::is_none")]
1216 pub z_mm: Option<f64>,
1217 #[serde(default, skip_serializing_if = "Option::is_none")]
1219 pub final_z_mm: Option<f64>,
1220 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1223 pub types: Vec<String>,
1224 #[serde(default, skip_serializing_if = "Option::is_none")]
1226 pub minutes_left: Option<i64>,
1227 #[serde(default, skip_serializing_if = "Option::is_none")]
1229 pub flow_factor: Option<SetValue>,
1230 #[serde(default, skip_serializing_if = "Option::is_none")]
1232 pub fan_percent: Option<SetValue>,
1233 #[serde(default, skip_serializing_if = "Option::is_none")]
1235 pub object_count: Option<usize>,
1236 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1240 pub objects: Vec<BedArea>,
1241 #[serde(default, skip_serializing_if = "Option::is_none")]
1244 pub rise: Option<Rise>,
1245 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1247 pub at_odds: Vec<PlanMismatch>,
1248 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1251 pub unknown: Vec<PlanFact>,
1252}
1253
1254impl Sample for SlicerPlan {
1255 fn sample_full() -> Self {
1256 Self {
1257 expected_color: Some("#FF0000".to_owned()),
1258 next_change: Some(PlannedChange::sample_full()),
1259 minutes_to_next_change: Some(17),
1260 change_waiting: Some(PlannedChange::sample_full()),
1261 layer: Some(12),
1262 z_mm: Some(2.4),
1263 types: vec![
1264 "Perimeter".to_owned(),
1265 "External perimeter".to_owned(),
1266 "Support material".to_owned(),
1267 ],
1268 final_z_mm: Some(30.0),
1269 minutes_left: Some(42),
1270 flow_factor: Some(SetValue {
1271 file: Some(1.0),
1272 changed: Some(0.95),
1273 }),
1274 fan_percent: Some(SetValue {
1275 file: Some(100.0),
1276 changed: None,
1277 }),
1278 object_count: Some(1),
1279 objects: vec![[100, 99, 150, 117]],
1280 rise: Some(Rise {
1281 since: Timestamp::sample_full(),
1282 mm: [7.2, 4.8],
1283 }),
1284 at_odds: vec![PlanMismatch::FlowLowOverWalls],
1285 unknown: vec![PlanFact::Objects],
1286 }
1287 }
1288
1289 fn sample_minimal() -> Self {
1290 Self {
1291 expected_color: None,
1292 next_change: None,
1293 minutes_to_next_change: None,
1294 change_waiting: None,
1295 layer: None,
1296 z_mm: None,
1297 final_z_mm: None,
1298 types: Vec::new(),
1299 minutes_left: None,
1300 flow_factor: None,
1301 fan_percent: None,
1302 object_count: None,
1303 objects: Vec::new(),
1304 rise: None,
1305 at_odds: Vec::new(),
1306 unknown: Vec::new(),
1307 }
1308 }
1309}
1310
1311#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1313enum Positioning {
1314 #[default]
1316 Absolute,
1317 Relative,
1319}
1320
1321#[derive(Debug, Default)]
1324pub struct IndexBuilder {
1325 line: Vec<u8>,
1327 overlong: bool,
1329 read: u64,
1331 lines: u64,
1333 layers: Vec<Layer>,
1335 type_names: Vec<String>,
1337 labelled_types: bool,
1339 current_type: Option<usize>,
1341 width_mm: f32,
1343 read_from: u64,
1346 time_left: Vec<Mark<i64>>,
1348 flow: Vec<Mark<f64>>,
1350 fan: Vec<Mark<f64>>,
1352 objects: Vec<ObjectDraft>,
1354 object_numbers: BTreeMap<i64, usize>,
1356 current_object: Option<usize>,
1359 labelled_objects: bool,
1361 at: [f64; 3],
1363 e: f64,
1365 axes: Positioning,
1367 extruder: Positioning,
1369 line_began: u64,
1371 all: Reach,
1373 blocks: Vec<(u64, usize)>,
1376 spool: Option<Spooling>,
1378 collected: Option<Vec<ToolpathSegment>>,
1380 trail: Option<Vec<[f64; 2]>>,
1383 reached_last: Option<[f64; 2]>,
1385 changes: Vec<ChangeDraft>,
1387 change_minutes: Vec<Mark<i64>>,
1389 colour_comment: Option<(u64, String)>,
1391 first_colour: Option<String>,
1393 extruded_mm: f64,
1395 laid_in_layers: usize,
1398}
1399
1400#[derive(Debug, Clone, PartialEq)]
1403struct ChangeDraft {
1404 kind: PlannedChangeKind,
1406 offset: u64,
1408 at: u64,
1410 layer: usize,
1413 color: Option<String>,
1415 fed_before_mm: f64,
1417}
1418
1419#[derive(Debug)]
1421struct Spooling {
1422 path: std::path::PathBuf,
1424 writer: std::io::BufWriter<std::fs::File>,
1426 failed: bool,
1428}
1429
1430impl GcodeSink for IndexBuilder {
1431 fn take(&mut self, piece: &[u8]) -> ControlFlow<()> {
1432 if let Some(spool) = self.spool.as_mut().filter(|spool| !spool.failed) {
1442 use std::io::Write as _;
1443 spool.failed = spool.writer.write_all(piece).is_err();
1444 }
1445 let mut start = 0;
1446 let mut at = 0;
1447 while at < piece.len() {
1448 if piece[at] == b'\n' {
1449 let head = &piece[start..at];
1450 self.read += u64::try_from(at + 1 - start).unwrap_or(u64::MAX);
1451 if self.line.is_empty() && !self.overlong {
1452 self.lines += 1;
1454 if head.len() <= LINE_LIMIT {
1455 self.read_line(head);
1456 }
1457 } else {
1458 self.hold(head);
1459 self.end_line();
1460 }
1461 self.line_began = self.read;
1462 start = at + 1;
1463 }
1464 at += 1;
1465 }
1466 let rest = &piece[start..];
1467 self.hold(rest);
1468 self.read += u64::try_from(rest.len()).unwrap_or(u64::MAX);
1469 ControlFlow::Continue(())
1470 }
1471}
1472
1473impl IndexBuilder {
1474 #[must_use]
1476 pub fn new() -> Self {
1477 Self::default()
1478 }
1479
1480 pub fn spooling(path: std::path::PathBuf) -> std::io::Result<Self> {
1488 let file = std::fs::File::create(&path)?;
1489 Ok(Self {
1490 spool: Some(Spooling {
1491 path,
1492 writer: std::io::BufWriter::with_capacity(1 << 16, file),
1493 failed: false,
1494 }),
1495 ..Self::default()
1496 })
1497 }
1498
1499 fn reading_layer(type_names: Vec<String>, head: Head, start: u64) -> Self {
1502 Self {
1503 type_names,
1504 labelled_types: true,
1505 current_type: head.current_type,
1506 width_mm: head.width_mm,
1507 read_from: start,
1508 at: head.at,
1509 e: head.e,
1510 axes: head.axes,
1511 extruder: head.extruder,
1512 collected: Some(Vec::new()),
1513 ..Self::default()
1514 }
1515 }
1516
1517 #[must_use]
1520 pub fn finish(mut self) -> GcodeIndex {
1521 if !self.line.is_empty() || self.overlong {
1522 self.end_line();
1523 }
1524 let mut drafts: Vec<Option<ObjectDraft>> = self.objects.into_iter().map(Some).collect();
1525 let mut objects = Vec::new();
1526 let mut outlines = Vec::new();
1527 let mut outline_of = vec![None; drafts.len()];
1528 for place in self.object_numbers.into_values() {
1529 let Some(draft) = drafts.get_mut(place).and_then(Option::take) else {
1530 continue;
1531 };
1532 let Some([least_x, least_y, most_x, most_y]) = draft.bounds else {
1533 continue;
1534 };
1535 objects.push([
1536 whole(tenth(least_x).floor()),
1537 whole(tenth(least_y).floor()),
1538 whole(tenth(most_x).ceil()),
1539 whole(tenth(most_y).ceil()),
1540 ]);
1541 outline_of[place] = Some(outlines.len());
1542 outlines.push(draft.reach.outline().unwrap_or(ObjectOutline {
1543 hull_mm: Vec::new(),
1544 }));
1545 }
1546 if !self.labelled_objects {
1547 outlines.extend(self.all.outline());
1548 }
1549 let blocks = self
1550 .blocks
1551 .into_iter()
1552 .map(|(start, place)| (start, outline_of.get(place).copied().flatten()))
1553 .collect();
1554 let spool = self.spool.and_then(|mut spool| {
1555 use std::io::Write as _;
1556 if spool.failed || spool.writer.flush().is_err() {
1557 drop(spool.writer);
1558 let _ = std::fs::remove_file(&spool.path);
1559 return None;
1560 }
1561 Some(spool.path)
1562 });
1563 let changes = (0_u32..)
1564 .zip(self.changes)
1565 .map(|(index, draft)| {
1566 let layer = draft.layer.min(self.layers.len().saturating_sub(1));
1569 ChangeMark {
1570 change: PlannedChange {
1571 index,
1572 kind: draft.kind,
1573 offset_bytes: draft.offset,
1574 layer: u32::try_from(layer + 1).unwrap_or(u32::MAX),
1575 z_mm: self
1576 .layers
1577 .get(layer)
1578 .and_then(|held| held.z_mm)
1579 .unwrap_or(0.0),
1580 color: draft.color,
1581 },
1582 at: draft.at,
1583 fed_before_mm: draft.fed_before_mm,
1584 }
1585 })
1586 .collect();
1587 GcodeIndex {
1588 bytes: self.read,
1589 lines: self.lines,
1590 changes,
1591 change_minutes: self.change_minutes,
1592 first_colour: self.first_colour,
1593 extruded_mm: self.extruded_mm,
1594 layers: self.layers,
1595 type_names: self.type_names,
1596 labelled_types: self.labelled_types,
1597 time_left: self.time_left,
1598 flow: self.flow,
1599 fan: self.fan,
1600 objects,
1601 labelled_objects: self.labelled_objects,
1602 outlines,
1603 blocks,
1604 spool,
1605 }
1606 }
1607
1608 fn hold(&mut self, bytes: &[u8]) {
1610 if self.overlong {
1611 return;
1612 }
1613 if self.line.len() + bytes.len() > LINE_LIMIT {
1614 self.overlong = true;
1615 self.line.clear();
1616 return;
1617 }
1618 self.line.extend_from_slice(bytes);
1619 }
1620
1621 fn end_line(&mut self) {
1623 self.lines += 1;
1624 let line = core::mem::take(&mut self.line);
1625 if !self.overlong {
1626 self.read_line(&line);
1627 }
1628 self.overlong = false;
1629 self.line = line;
1630 self.line.clear();
1631 }
1632
1633 fn read_line(&mut self, raw: &[u8]) {
1635 let raw = raw.trim_ascii();
1636 if let Some(comment) = raw.strip_prefix(b";") {
1637 if let Ok(comment) = core::str::from_utf8(comment) {
1638 self.comment(comment.trim_end());
1639 }
1640 return;
1641 }
1642 if let [b'G', code @ b'0'..=b'3', b' ', rest @ ..] = raw {
1645 self.motion(u32::from(code - b'0'), &move_of(rest));
1646 return;
1647 }
1648 let held = words(raw);
1649 let mut words = held.as_slice();
1650 if let Some((Word { letter: b'N', .. }, rest)) = words.split_first() {
1652 words = rest;
1653 }
1654 let Some(first) = words.first() else {
1655 return;
1656 };
1657 let code = if held.numbered {
1658 held.second_code
1659 } else {
1660 held.first_code
1661 };
1662 match (char::from(first.letter), code) {
1663 ('G', Some(code @ 0..=3)) => self.motion(code, &Move::of(&words[1..])),
1664 ('G', Some(28)) => self.home(&words[1..]),
1665 ('G', Some(90)) => self.axes = Positioning::Absolute,
1666 ('G', Some(91)) => self.axes = Positioning::Relative,
1667 ('G', Some(92)) => self.declare(&words[1..]),
1668 ('M', Some(82)) => self.extruder = Positioning::Absolute,
1669 ('M', Some(83)) => self.extruder = Positioning::Relative,
1670 ('M', Some(73)) => self.estimate(&words[1..]),
1671 ('M', Some(221)) => self.flow_factor(&words[1..]),
1672 ('M', Some(106)) => self.fan_speed(&words[1..], Fan::Set),
1673 ('M', Some(107)) => self.fan_speed(&words[1..], Fan::Off),
1674 ('M', Some(486)) => self.object(raw, &words[1..]),
1675 ('M', Some(600)) => self.planned(PlannedChangeKind::ColorChange),
1676 ('M', Some(601)) => self.planned(PlannedChangeKind::Pause),
1677 _ => {}
1678 }
1679 }
1680
1681 fn comment(&mut self, comment: &str) {
1683 if comment == "LAYER_CHANGE" {
1684 self.layers.push(Layer {
1685 begins: self.line_began,
1686 head: Head {
1687 at: self.at,
1688 e: self.e,
1689 axes: self.axes,
1690 extruder: self.extruder,
1691 current_type: self.current_type,
1692 width_mm: self.width_mm,
1693 },
1694 at: self.read,
1695 z_mm: None,
1696 types: 0,
1697 });
1698 } else if let Some(z) = comment.strip_prefix("Z:") {
1699 if let Some(layer) = self.layers.last_mut()
1700 && layer.z_mm.is_none()
1701 {
1702 layer.z_mm = z
1705 .trim()
1706 .parse::<f64>()
1707 .ok()
1708 .filter(|z| (0.0..=AXIS_LIMIT).contains(z));
1709 }
1710 } else if let Some(change) = comment.strip_prefix("COLOR_CHANGE,") {
1711 self.colour_comment = change
1713 .split(',')
1714 .nth(1)
1715 .and_then(colour_of)
1716 .map(|colour| (self.lines, colour));
1717 } else if let Some(colours) = comment.trim_start().strip_prefix("filament_colour = ") {
1718 if self.first_colour.is_none() {
1719 self.first_colour = colours.split(';').next().and_then(colour_of);
1720 }
1721 } else if let Some(width) = comment.strip_prefix("WIDTH:") {
1722 #[expect(
1725 clippy::cast_possible_truncation,
1726 reason = "an extrusion width is drawn, not measured"
1727 )]
1728 if let Some(width) = width
1729 .trim()
1730 .parse::<f64>()
1731 .ok()
1732 .filter(|width| (0.0..=AXIS_LIMIT).contains(width))
1733 {
1734 self.width_mm = width as f32;
1735 }
1736 } else if let Some(name) = comment.strip_prefix("TYPE:") {
1737 let name = name.trim();
1738 self.labelled_types = true;
1739 self.current_type = if name == NOT_THE_PART {
1740 None
1741 } else {
1742 self.intern(name)
1743 };
1744 }
1745 }
1746
1747 fn intern(&mut self, name: &str) -> Option<usize> {
1749 if let Some(bit) = self.type_names.iter().position(|held| held == name) {
1750 return Some(bit);
1751 }
1752 if self.type_names.len() >= TYPE_LIMIT {
1753 return None;
1754 }
1755 self.type_names.push(name.to_owned());
1756 Some(self.type_names.len() - 1)
1757 }
1758
1759 fn motion(&mut self, code: u32, words: &Move) {
1761 let start = self.at;
1764 let relative = self.axes == Positioning::Relative;
1765 if let Some(x) = words.x {
1766 self.place(0, x, relative);
1767 }
1768 if let Some(y) = words.y {
1769 self.place(1, y, relative);
1770 }
1771 if let Some(z) = words.z {
1772 self.place(2, z, relative);
1773 }
1774 let mut fed = 0.0;
1775 if let Some(value) = words.e {
1776 if relative || self.extruder == Positioning::Relative {
1777 self.e += value;
1778 fed = value;
1779 } else {
1780 fed = value - self.e;
1781 self.e = value;
1782 }
1783 }
1784 let travel = (self.at[0] - start[0]).hypot(self.at[1] - start[1]);
1785 if let Some(trail) = self.trail.as_mut()
1786 && travel > 0.0
1787 {
1788 trail.push([self.at[0], self.at[1]]);
1789 }
1790 self.extruded_mm += fed;
1791 if fed <= 0.0 || (travel <= TRAVEL_MM && code < 2) {
1792 return;
1793 }
1794 self.laid_in_layers = self.layers.len();
1795 if let (Some(layer), Some(bit)) = (self.layers.last_mut(), self.current_type) {
1796 layer.types |= 1 << bit;
1797 }
1798 let end = self.at;
1799 let turn = match code {
1800 2 => Some(Turn::Clockwise),
1801 3 => Some(Turn::CounterClockwise),
1802 _ => None,
1803 };
1804 let arc = turn.and_then(|turn| arc_of(words, turn, start, end));
1805 if let Some(collected) = self.collected.as_mut() {
1806 let kind = self
1807 .current_type
1808 .and_then(|bit| self.type_names.get(bit))
1809 .map_or(ExtrusionKind::Other, |name| ExtrusionKind::of_type(name));
1810 let laid = Laid {
1811 kind,
1812 width_mm: self.width_mm,
1813 ends_at: self.read_from.saturating_add(self.read),
1814 };
1815 collect_segments(collected, laid, start, end, arc);
1816 return;
1817 }
1818 let part_of_plan = !(self.labelled_types && self.current_type.is_none());
1819 let reach = if let Some(object) = self.current_object {
1820 let draft = &mut self.objects[object];
1821 grow(&mut draft.bounds, start[0], start[1]);
1822 grow(&mut draft.bounds, end[0], end[1]);
1823 if let Some(turn) = turn {
1824 for [x, y] in arc_extremes(words, turn, start, end) {
1825 grow(&mut draft.bounds, x, y);
1826 }
1827 }
1828 &mut draft.reach
1829 } else if !self.labelled_objects && part_of_plan {
1830 &mut self.all
1831 } else {
1832 return;
1833 };
1834 if self.reached_last != Some([start[0], start[1]]) {
1837 reach.point(start[0], start[1]);
1838 }
1839 reach.point(end[0], end[1]);
1840 self.reached_last = Some([end[0], end[1]]);
1841 if let Some(arc) = arc {
1842 reach.arc(arc.centre, arc.radius, arc.base, arc.sweep);
1843 }
1844 }
1845
1846 fn place(&mut self, axis: usize, value: f64, relative: bool) {
1850 let landed = if relative {
1851 self.at[axis] + value
1852 } else {
1853 value
1854 };
1855 if landed.abs() <= AXIS_LIMIT {
1856 self.at[axis] = landed;
1857 }
1858 }
1859
1860 fn home(&mut self, words: &[Word]) {
1862 let named: Vec<usize> = ['X', 'Y', 'Z']
1863 .into_iter()
1864 .enumerate()
1865 .filter(|(_, letter)| words.iter().any(|word| char::from(word.letter) == *letter))
1866 .map(|(axis, _)| axis)
1867 .collect();
1868 if named.is_empty() {
1869 self.at = [0.0; 3];
1870 } else {
1871 for axis in named {
1872 self.at[axis] = 0.0;
1873 }
1874 }
1875 }
1876
1877 fn declare(&mut self, words: &[Word]) {
1880 if words.is_empty() {
1881 self.at = [0.0; 3];
1882 self.e = 0.0;
1883 return;
1884 }
1885 for (axis, letter) in ['X', 'Y', 'Z'].into_iter().enumerate() {
1886 if let Some(value) = number(words, letter).filter(|value| value.abs() <= AXIS_LIMIT) {
1887 self.at[axis] = value;
1888 }
1889 }
1890 if let Some(value) = number(words, 'E') {
1891 self.e = value;
1892 }
1893 }
1894
1895 fn estimate(&mut self, words: &[Word]) {
1898 if let Some(minutes) = number(words, 'C').filter(|minutes| *minutes >= 0.0) {
1899 self.change_minutes.push(Mark {
1900 at: self.read,
1901 value: whole(minutes),
1902 });
1903 }
1904 if number(words, 'P').is_none() {
1905 return;
1906 }
1907 if let Some(minutes) = number(words, 'R').filter(|minutes| *minutes >= 0.0) {
1908 self.time_left.push(Mark {
1909 at: self.read,
1910 value: whole(minutes),
1911 });
1912 }
1913 }
1914
1915 fn planned(&mut self, kind: PlannedChangeKind) {
1918 let named = self.colour_comment.take();
1919 if self.changes.len() >= CHANGE_LIMIT {
1920 return;
1921 }
1922 let color = match kind {
1923 PlannedChangeKind::ColorChange => named
1924 .filter(|(line, _)| line + 1 == self.lines)
1925 .map(|(_, colour)| colour),
1926 PlannedChangeKind::Pause => None,
1927 };
1928 let layer = if self.laid_in_layers == self.layers.len() {
1929 self.layers.len()
1930 } else {
1931 self.layers.len() - 1
1932 };
1933 self.changes.push(ChangeDraft {
1934 kind,
1935 offset: self.line_began,
1936 at: self.read,
1937 layer,
1938 color,
1939 fed_before_mm: self.extruded_mm,
1940 });
1941 }
1942
1943 fn flow_factor(&mut self, words: &[Word]) {
1945 if let Some(percent) = number(words, 'S').filter(|percent| *percent >= 0.0) {
1946 mark_setting(&mut self.flow, self.read, percent / 100.0);
1947 }
1948 }
1949
1950 fn fan_speed(&mut self, words: &[Word], command: Fan) {
1952 if number(words, 'P').is_some_and(|fan| fan != 0.0) {
1953 return;
1954 }
1955 let speed = match command {
1956 Fan::Off => 0.0,
1957 Fan::Set => number(words, 'S').unwrap_or(FAN_FULL),
1958 };
1959 let percent = (speed.clamp(0.0, FAN_FULL) / FAN_FULL * 100.0).round();
1960 mark_setting(&mut self.fan, self.read, percent);
1961 }
1962
1963 fn object(&mut self, raw: &[u8], words: &[Word]) {
1965 if raw
1968 .strip_prefix(b"M486")
1969 .is_some_and(|rest| rest.trim_ascii_start().starts_with(b"A"))
1970 {
1971 self.labelled_objects = true;
1972 return;
1973 }
1974 let Some(number) = number(words, 'S')
1977 .filter(|number| (number - number.round()).abs() < f64::EPSILON && *number >= -1.0)
1978 else {
1979 return;
1980 };
1981 self.labelled_objects = true;
1982 if number < 0.0 {
1983 self.current_object = None;
1984 self.reached_last = None;
1985 return;
1986 }
1987 let id = whole(number);
1988 let place = if let Some(place) = self.object_numbers.get(&id) {
1989 *place
1990 } else if self.objects.len() >= OBJECT_LIMIT {
1991 self.current_object = None;
1992 self.reached_last = None;
1993 return;
1994 } else {
1995 self.objects.push(ObjectDraft::default());
1996 self.object_numbers.insert(id, self.objects.len() - 1);
1997 self.objects.len() - 1
1998 };
1999 self.current_object = Some(place);
2000 self.reached_last = None;
2001 self.blocks.push((self.read, place));
2002 }
2003}
2004
2005fn colour_of(text: &str) -> Option<String> {
2007 let text = text.trim();
2008 let hex = text.strip_prefix('#')?;
2009 (hex.len() == 6 && hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
2010 .then(|| text.to_ascii_uppercase())
2011}
2012
2013fn mark_setting(marks: &mut Vec<Mark<f64>>, at: u64, value: f64) {
2017 marks.push(Mark { at, value });
2018}
2019
2020fn whole(value: f64) -> i64 {
2023 format!("{:.0}", value.round()).parse().unwrap_or_default()
2024}
2025
2026fn tenth(value: f64) -> f64 {
2030 (value * 10.0).round() / 10.0
2031}
2032
2033fn grow(bounds: &mut Option<[f64; 4]>, x: f64, y: f64) {
2035 *bounds = Some(match *bounds {
2036 None => [x, y, x, y],
2037 Some([least_x, least_y, most_x, most_y]) => {
2038 [least_x.min(x), least_y.min(y), most_x.max(x), most_y.max(y)]
2039 }
2040 });
2041}
2042
2043#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2045enum Turn {
2046 Clockwise,
2048 CounterClockwise,
2050}
2051
2052#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2055enum Fan {
2056 Set,
2058 Off,
2060}
2061
2062fn arc_extremes(
2071 words: &Move,
2072 turn: Turn,
2073 start: [f64; 3],
2074 end: [f64; 3],
2075) -> impl Iterator<Item = [f64; 2]> {
2076 let reach = arc_of(words, turn, start, end).map(|arc| {
2077 let ArcGeometry {
2078 centre,
2079 radius,
2080 base,
2081 sweep,
2082 ..
2083 } = arc;
2084 let tau = core::f64::consts::TAU;
2085 (0..4).filter_map(move |quarter| {
2086 let angle = core::f64::consts::FRAC_PI_2 * f64::from(quarter);
2087 ((angle - base).rem_euclid(tau) <= sweep + 1e-9).then(|| {
2088 [
2089 centre[0] + radius * angle.cos(),
2090 centre[1] + radius * angle.sin(),
2091 ]
2092 })
2093 })
2094 });
2095 reach.into_iter().flatten()
2096}
2097
2098#[derive(Debug, Clone, Copy)]
2100struct ArcGeometry {
2101 centre: [f64; 2],
2103 radius: f64,
2105 base: f64,
2108 sweep: f64,
2111 turn: Turn,
2113}
2114
2115fn arc_of(words: &Move, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<ArcGeometry> {
2119 let centre = words.r.map_or_else(
2120 || {
2121 Some([
2122 start[0] + words.i.unwrap_or(0.0),
2123 start[1] + words.j.unwrap_or(0.0),
2124 ])
2125 },
2126 |radius| centre_of_radius(radius, turn, start, end),
2127 )?;
2128 let radius = (start[0] - centre[0]).hypot(start[1] - centre[1]);
2129 let from = (start[1] - centre[1]).atan2(start[0] - centre[0]);
2130 let to = (end[1] - centre[1]).atan2(end[0] - centre[0]);
2131 let tau = core::f64::consts::TAU;
2132 let (base, sweep) = match turn {
2135 Turn::Clockwise => (to, (from - to).rem_euclid(tau)),
2136 Turn::CounterClockwise => (from, (to - from).rem_euclid(tau)),
2137 };
2138 let sweep = if sweep < 1e-9 { tau } else { sweep };
2139 Some(ArcGeometry {
2140 centre,
2141 radius,
2142 base,
2143 sweep,
2144 turn,
2145 })
2146}
2147
2148#[derive(Debug, Clone, Copy)]
2150struct Laid {
2151 kind: ExtrusionKind,
2153 width_mm: f32,
2155 ends_at: u64,
2157}
2158
2159fn collect_segments(
2162 collected: &mut Vec<ToolpathSegment>,
2163 laid: Laid,
2164 start: [f64; 3],
2165 end: [f64; 3],
2166 arc: Option<ArcGeometry>,
2167) {
2168 #[expect(
2169 clippy::cast_possible_truncation,
2170 reason = "bed millimetres are far inside f32's range; a toolpath is drawn, not measured"
2171 )]
2172 let at = |x: f64, y: f64| [x as f32, y as f32];
2173 let Some(arc) = arc else {
2174 collected.push(ToolpathSegment {
2175 from_mm: at(start[0], start[1]),
2176 to_mm: at(end[0], end[1]),
2177 kind: laid.kind,
2178 width_mm: laid.width_mm,
2179 ends_at: laid.ends_at,
2180 });
2181 return;
2182 };
2183 let length = arc.sweep * arc.radius;
2184 let chords = (length / CHORD_MM).ceil().clamp(1.0, 4096.0);
2185 let (from, step) = match arc.turn {
2186 Turn::CounterClockwise => (arc.base, arc.sweep / chords),
2187 Turn::Clockwise => (arc.base + arc.sweep, -arc.sweep / chords),
2188 };
2189 let mut previous = at(start[0], start[1]);
2190 let mut k = 1.0;
2191 while k < chords {
2192 let angle = from + step * k;
2193 let next = at(
2194 arc.centre[0] + arc.radius * angle.cos(),
2195 arc.centre[1] + arc.radius * angle.sin(),
2196 );
2197 collected.push(ToolpathSegment {
2198 from_mm: previous,
2199 to_mm: next,
2200 kind: laid.kind,
2201 width_mm: laid.width_mm,
2202 ends_at: laid.ends_at,
2203 });
2204 previous = next;
2205 k += 1.0;
2206 }
2207 collected.push(ToolpathSegment {
2208 from_mm: previous,
2209 to_mm: at(end[0], end[1]),
2210 kind: laid.kind,
2211 width_mm: laid.width_mm,
2212 ends_at: laid.ends_at,
2213 });
2214}
2215
2216fn centre_of_radius(radius: f64, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<[f64; 2]> {
2221 let chord = [end[0] - start[0], end[1] - start[1]];
2222 let length = chord[0].hypot(chord[1]);
2223 if length <= TRAVEL_MM || length > 2.0 * radius.abs() {
2224 return None;
2225 }
2226 let rise = (radius * radius - length * length / 4.0).max(0.0).sqrt();
2227 let left = match turn {
2228 Turn::Clockwise => -1.0,
2229 Turn::CounterClockwise => 1.0,
2230 };
2231 let side = left * radius.signum() * rise / length;
2232 Some([
2233 start[0] + chord[0] / 2.0 - chord[1] * side,
2234 start[1] + chord[1] / 2.0 + chord[0] * side,
2235 ])
2236}
2237
2238fn words(command: &[u8]) -> Words {
2244 let mut found = Words {
2245 held: [Word {
2246 letter: 0,
2247 value: f64::NAN,
2248 }; WORD_COUNT],
2249 len: 0,
2250 first_code: None,
2251 second_code: None,
2252 numbered: false,
2253 };
2254 let length = command.len();
2255 let mut at = 0;
2256 while at < length {
2257 let letter = command[at];
2258 if letter == b';' || letter == b'*' {
2259 break;
2260 }
2261 at += 1;
2262 let upper = match letter {
2263 b'a'..=b'z' => letter - (b'a' - b'A'),
2264 b'A'..=b'Z' => letter,
2265 _ => continue,
2266 };
2267 let start = at;
2268 let (value, next) = number_at(command, at);
2269 at = next;
2270 let text = &command[start..at];
2271 if found.len == 0 {
2274 found.first_code = whole_number(text);
2275 found.numbered = upper == b'N';
2276 } else if found.len == 1 {
2277 found.second_code = whole_number(text);
2278 }
2279 if found.len < WORD_COUNT {
2280 found.held[found.len] = Word {
2281 letter: upper,
2282 value,
2283 };
2284 found.len += 1;
2285 }
2286 }
2287 found
2288}
2289
2290fn number_at(line: &[u8], mut at: usize) -> (f64, usize) {
2299 let start = at;
2300 while at < line.len()
2301 && !matches!(line[at], b' ' | b'\t' | b';' | b'*' | b'A'..=b'Z' | b'a'..=b'z')
2302 {
2303 at += 1;
2304 }
2305 (decimal(&line[start..at]).unwrap_or(f64::NAN), at)
2306}
2307
2308#[derive(Debug, Clone, Copy, Default)]
2312struct Move {
2313 x: Option<f64>,
2315 y: Option<f64>,
2317 z: Option<f64>,
2319 e: Option<f64>,
2321 i: Option<f64>,
2323 j: Option<f64>,
2325 r: Option<f64>,
2327}
2328
2329impl Move {
2330 fn of(words: &[Word]) -> Self {
2332 Self {
2333 x: number(words, 'X'),
2334 y: number(words, 'Y'),
2335 z: number(words, 'Z'),
2336 e: number(words, 'E'),
2337 i: number(words, 'I'),
2338 j: number(words, 'J'),
2339 r: number(words, 'R'),
2340 }
2341 }
2342}
2343
2344fn move_of(line: &[u8]) -> Move {
2349 let mut found = Move::default();
2350 let length = line.len();
2351 let mut at = 0;
2352 while at < length {
2353 let letter = line[at];
2354 at += 1;
2355 let slot = match letter {
2356 b';' | b'*' => break,
2357 b'X' | b'x' => &mut found.x,
2358 b'Y' | b'y' => &mut found.y,
2359 b'Z' | b'z' => &mut found.z,
2360 b'E' | b'e' => &mut found.e,
2361 b'I' | b'i' => &mut found.i,
2362 b'J' | b'j' => &mut found.j,
2363 b'R' | b'r' => &mut found.r,
2364 b'A'..=b'Z' | b'a'..=b'z' => {
2365 while at < length && !matches!(line[at], b' ' | b'\t' | b';' | b'*') {
2366 at += 1;
2367 }
2368 continue;
2369 }
2370 _ => continue,
2371 };
2372 let (value, next) = number_at(line, at);
2373 at = next;
2374 if slot.is_none() {
2375 *slot = Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
2376 }
2377 }
2378 found
2379}
2380
2381#[derive(Debug, Clone, Copy)]
2384struct Word {
2385 letter: u8,
2387 value: f64,
2389}
2390
2391struct Words {
2393 held: [Word; WORD_COUNT],
2395 len: usize,
2397 first_code: Option<u32>,
2399 second_code: Option<u32>,
2401 numbered: bool,
2403}
2404
2405impl Words {
2406 fn as_slice(&self) -> &[Word] {
2408 &self.held[..self.len]
2409 }
2410}
2411
2412fn whole_number(text: &[u8]) -> Option<u32> {
2414 let mut value: u32 = 0;
2415 let mut at = 0;
2416 while at < text.len() {
2417 let byte = text[at];
2418 if !byte.is_ascii_digit() {
2419 return None;
2420 }
2421 value = value.checked_mul(10)?.checked_add(u32::from(byte - b'0'))?;
2422 at += 1;
2423 }
2424 (!text.is_empty()).then_some(value)
2425}
2426
2427fn decimal(text: &[u8]) -> Option<f64> {
2429 core::str::from_utf8(text).ok()?.parse::<f64>().ok()
2430}
2431
2432fn number(words: &[Word], letter: char) -> Option<f64> {
2435 let mut at = 0;
2436 while at < words.len() {
2437 let Word {
2438 letter: word,
2439 value,
2440 } = words[at];
2441 if char::from(word) == letter {
2442 return Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
2443 }
2444 at += 1;
2445 }
2446 None
2447}
2448
2449#[must_use]
2452pub fn index_of(pieces: &[&[u8]]) -> GcodeIndex {
2453 let mut builder = IndexBuilder::new();
2454 for piece in pieces {
2455 let _ = builder.take(piece);
2456 }
2457 builder.finish()
2458}
2459
2460#[derive(Debug, Default)]
2462enum Slot {
2463 #[default]
2465 Empty,
2466 Building(Vec<Waker>),
2468 Ready(Arc<GcodeIndex>),
2470}
2471
2472#[derive(Debug, Default)]
2474pub struct GcodeIndexes {
2475 slots: Mutex<BTreeMap<PrintId, Slot>>,
2477 looked: Mutex<BTreeMap<PrintId, Vec<(Timestamp, i64)>>>,
2483}
2484
2485#[derive(Debug)]
2487pub enum Claimed<'a> {
2488 Ready(Arc<GcodeIndex>),
2490 Build(BuildClaim<'a>),
2492}
2493
2494#[derive(Debug)]
2497pub struct BuildClaim<'a> {
2498 indexes: &'a GcodeIndexes,
2500 print_id: PrintId,
2502 done: bool,
2504}
2505
2506impl BuildClaim<'_> {
2507 #[must_use]
2509 pub fn finish(mut self, index: GcodeIndex) -> Arc<GcodeIndex> {
2510 let index = Arc::new(index);
2511 self.settle(Slot::Ready(Arc::clone(&index)));
2512 self.done = true;
2513 index
2514 }
2515
2516 fn settle(&self, next: Slot) {
2518 let waiting = {
2519 let mut slots = self.indexes.held();
2520 let slot = slots.entry(self.print_id).or_default();
2521 match core::mem::replace(slot, next) {
2522 Slot::Building(waiting) => waiting,
2523 Slot::Empty | Slot::Ready(_) => Vec::new(),
2524 }
2525 };
2526 for waker in waiting {
2527 waker.wake();
2528 }
2529 }
2530}
2531
2532impl Drop for BuildClaim<'_> {
2533 fn drop(&mut self) {
2534 if !self.done {
2535 self.settle(Slot::Empty);
2536 }
2537 }
2538}
2539
2540impl GcodeIndexes {
2541 fn held(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, Slot>> {
2543 self.slots.lock().unwrap_or_else(PoisonError::into_inner)
2544 }
2545
2546 pub const fn claim(&self, print_id: PrintId) -> Claim<'_> {
2549 Claim {
2550 indexes: self,
2551 print_id,
2552 }
2553 }
2554
2555 #[must_use]
2557 pub fn built(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
2558 match self.held().get(&print_id) {
2559 Some(Slot::Ready(index)) => Some(Arc::clone(index)),
2560 _ => None,
2561 }
2562 }
2563}
2564
2565#[derive(Debug)]
2567pub struct Claim<'a> {
2568 indexes: &'a GcodeIndexes,
2570 print_id: PrintId,
2572}
2573
2574impl<'a> Future for Claim<'a> {
2575 type Output = Claimed<'a>;
2576
2577 fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
2578 let mut slots = self.indexes.held();
2579 let slot = slots.entry(self.print_id).or_default();
2580 match slot {
2581 Slot::Ready(index) => Poll::Ready(Claimed::Ready(Arc::clone(index))),
2582 Slot::Building(waiting) => {
2583 if !waiting.iter().any(|held| held.will_wake(context.waker())) {
2584 waiting.push(context.waker().clone());
2585 }
2586 Poll::Pending
2587 }
2588 Slot::Empty => {
2589 *slot = Slot::Building(Vec::new());
2590 Poll::Ready(Claimed::Build(BuildClaim {
2591 indexes: self.indexes,
2592 print_id: self.print_id,
2593 done: false,
2594 }))
2595 }
2596 }
2597 }
2598}
2599
2600const HELD_INDEXES: usize = 16;
2604
2605impl GcodeIndexes {
2606 pub(crate) fn note_look(
2612 &self,
2613 print_id: PrintId,
2614 captured: Timestamp,
2615 position: i64,
2616 now: Timestamp,
2617 ) {
2618 let mut looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
2619 let frames = looked.entry(print_id).or_default();
2620 frames.push((captured, position));
2621 frames.sort_by_key(|(captured, _)| *captured);
2622 if let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) {
2623 let aged = frames.partition_point(|(captured, _)| *captured <= until);
2624 frames.drain(..aged.saturating_sub(1));
2625 }
2626 while looked.len() > HELD_INDEXES {
2627 let Some(oldest) = looked.keys().next().copied() else {
2628 break;
2629 };
2630 let _ = looked.remove(&oldest);
2631 }
2632 }
2633
2634 fn newest_look_until(&self, print_id: PrintId, until: Timestamp) -> Option<(Timestamp, i64)> {
2637 let looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
2638 looked
2639 .get(&print_id)?
2640 .iter()
2641 .rev()
2642 .find(|(captured, _)| *captured <= until)
2643 .copied()
2644 }
2645
2646 fn trim(&self, keep: PrintId) {
2648 let mut slots = self.held();
2649 let ready: Vec<PrintId> = slots
2650 .iter()
2651 .filter(|(print_id, slot)| **print_id != keep && matches!(slot, Slot::Ready(_)))
2652 .map(|(print_id, _)| *print_id)
2653 .collect();
2654 let over = slots.len().saturating_sub(HELD_INDEXES);
2655 for print_id in ready.into_iter().take(over) {
2656 slots.remove(&print_id);
2657 }
2658 }
2659}
2660
2661impl crate::supervisor::Supervisor {
2662 pub(crate) async fn slicer_plan(
2674 &self,
2675 print: &crate::records::PrintRecord,
2676 job: Option<&printobserver_printer_api::JobSnapshot>,
2677 interventions: &[crate::records::Intervention],
2678 ) -> Result<Option<SlicerPlan>, crate::error::CoreError> {
2679 let Some((position, file)) = job
2680 .and_then(|job| job.file_position_bytes.zip(job.file_name.as_deref()))
2681 .filter(|(_, file)| {
2682 print.ended_at.is_none() && print.file_name.as_deref() == Some(*file)
2683 })
2684 else {
2685 return Ok(None);
2686 };
2687 let Some(index) = self.index_of(print.id, file).await else {
2688 return Ok(None);
2689 };
2690 let (flow, fan) = self
2691 .changes_since(print.id, &index, position, interventions)
2692 .await?;
2693 let mut plan = index.plan_with(position, flow, fan);
2694 plan.change_waiting = self
2695 .planned_change_waiting(print.id)
2696 .await?
2697 .map(|waiting| waiting.reached.change);
2698 plan.rise = self.rise_of(print.id, &index, position).await?;
2699 if plan.rise.is_none() {
2700 plan.unknown.push(PlanFact::Rise);
2701 plan.unknown.sort_unstable();
2702 }
2703 Ok(Some(plan))
2704 }
2705
2706 async fn rise_of(
2711 &self,
2712 print_id: PrintId,
2713 index: &GcodeIndex,
2714 position: i64,
2715 ) -> Result<Option<Rise>, crate::error::CoreError> {
2716 use printobserver_types::EventPayload as _;
2717
2718 use crate::kinds::PeriodicObservationPayload;
2719
2720 let now = self.clock().now();
2721 let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) else {
2722 return Ok(None);
2723 };
2724 let events = self
2725 .stores()
2726 .events
2727 .history(crate::store::HistoryQuery {
2728 print_id,
2729 kinds: printobserver_types::EventKind::new(PeriodicObservationPayload::KIND)
2730 .into_iter()
2731 .collect(),
2732 since: None,
2733 until: Some(until),
2734 limit: Some(1),
2735 })
2736 .await?;
2737 let observed = events.first().and_then(|event| {
2738 let observed = event.payload_as::<PeriodicObservationPayload>()?.ok()?;
2739 let earlier = observed.job?.file_position_bytes?;
2740 Some((
2741 observed.frame_captured_at.unwrap_or(event.received_at),
2742 earlier,
2743 ))
2744 });
2745 let looked = self.gcode_indexes().newest_look_until(print_id, until);
2746 let newest = match (observed, looked) {
2747 (Some(observed), Some(looked)) => Some(if looked.0 > observed.0 {
2748 looked
2749 } else {
2750 observed
2751 }),
2752 (observed, looked) => observed.or(looked),
2753 };
2754 Ok(newest.and_then(|(since, earlier)| {
2755 Some(Rise {
2756 since,
2757 mm: index.height_and_rise_since(earlier, position)?,
2758 })
2759 }))
2760 }
2761
2762 pub async fn print_gcode_index(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
2767 let print = self.stores().prints.print(print_id).await.ok()??;
2774 if print.ended_at.is_some() {
2775 return None;
2776 }
2777 self.index_of(print.id, print.file_name.as_deref()?).await
2778 }
2779
2780 pub(crate) fn drop_gcode_spool(&self, print_id: PrintId) {
2782 if let Some(directory) = self.config().gcode_spool_dir.as_deref() {
2783 let _ = std::fs::remove_file(crate::toolpath::spool_path(directory, print_id));
2784 }
2785 }
2786
2787 pub async fn sweep_gcode_spools(&self) -> Result<(), crate::error::CoreError> {
2794 let Some(directory) = self.config().gcode_spool_dir.clone() else {
2795 return Ok(());
2796 };
2797 let open: Vec<String> = self
2798 .stores()
2799 .prints
2800 .open_prints()
2801 .await?
2802 .iter()
2803 .map(|print| print.id.to_string())
2804 .collect();
2805 let Ok(entries) = std::fs::read_dir(&directory) else {
2813 return Ok(());
2814 };
2815 for entry in entries.flatten() {
2816 let name = entry.file_name();
2817 let Some(print) = name
2819 .to_str()
2820 .and_then(|name| name.strip_suffix(crate::toolpath::SPOOL_SUFFIX))
2821 .filter(|print| print.parse::<PrintId>().is_ok())
2822 else {
2823 continue;
2824 };
2825 if !open.iter().any(|id| id == print) {
2826 let _ = std::fs::remove_file(entry.path());
2827 }
2828 }
2829 Ok(())
2830 }
2831
2832 async fn index_of(&self, print_id: PrintId, file: &str) -> Option<Arc<GcodeIndex>> {
2834 let file_name = printobserver_types::FileName::new(file).ok()?;
2836 let claim = match self.gcode_indexes().claim(print_id).await {
2837 Claimed::Ready(index) => return Some(index),
2838 Claimed::Build(claim) => claim,
2839 };
2840 let mut builder = self
2843 .config()
2844 .gcode_spool_dir
2845 .as_deref()
2846 .and_then(|directory| {
2847 IndexBuilder::spooling(crate::toolpath::spool_path(directory, print_id)).ok()
2848 })
2849 .unwrap_or_default();
2850 self.read_gcode(file_name.clone(), &mut builder)
2851 .await
2852 .ok()?;
2853 let index = claim.finish(builder.finish());
2854 self.gcode_indexes().trim(print_id);
2855 if let Ok(body) = printobserver_types::EventBody::of(&crate::kinds::GcodeIndexedPayload {
2856 file_name,
2857 bytes: index.bytes(),
2858 layers: u64::try_from(index.layer_count()).unwrap_or(u64::MAX),
2859 }) {
2860 let _ = self.append_system_event(print_id, body).await;
2863 }
2864 Some(index)
2865 }
2866
2867 async fn changes_since(
2876 &self,
2877 print_id: PrintId,
2878 index: &GcodeIndex,
2879 position: i64,
2880 interventions: &[crate::records::Intervention],
2881 ) -> Result<(Option<f64>, Option<f64>), crate::error::CoreError> {
2882 use printobserver_types::EventPayload as _;
2883
2884 use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload};
2885 use crate::records::PrintAction;
2886
2887 let kinds = [ActionRequestedPayload::KIND, ActionExecutedPayload::KIND]
2888 .iter()
2889 .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
2890 .collect();
2891 let events = self
2892 .stores()
2893 .events
2894 .history(crate::store::HistoryQuery {
2895 print_id,
2896 kinds,
2897 since: None,
2898 until: None,
2899 limit: Some(crate::store::MAX_HISTORY_LIMIT),
2900 })
2901 .await?;
2902 let requested: BTreeMap<crate::records::ActionId, PrintAction> = events
2903 .iter()
2904 .filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
2905 .filter_map(Result::ok)
2906 .map(|payload| (payload.action_id, payload.action))
2907 .collect();
2908 let mut flow = None;
2909 let mut fan = None;
2910 for executed in events
2912 .iter()
2913 .filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
2914 .filter_map(Result::ok)
2915 {
2916 let standing = executed
2917 .intervention_id
2918 .is_none_or(|opened| interventions.iter().any(|active| active.id == opened));
2919 let made = executed
2922 .file_position_bytes
2923 .and_then(|made| u64::try_from(made).ok())
2924 .unwrap_or(0);
2925 let after = |set: Option<SetInFile>| set.is_none_or(|set| made >= set.at);
2926 match requested.get(&executed.action_id) {
2927 Some(PrintAction::SetFlowrateFactor { factor, .. }) if flow.is_none() => {
2928 flow = Some((standing && after(index.flow_at(position))).then_some(*factor));
2929 }
2930 Some(PrintAction::SetFanPercent { percent, .. }) if fan.is_none() => {
2931 fan = Some((standing && after(index.fan_at(position))).then_some(*percent));
2932 }
2933 _ => {}
2934 }
2935 }
2936 Ok((flow.flatten(), fan.flatten()))
2937 }
2938}
2939
2940#[cfg(test)]
2941mod tests {
2942 use super::{GcodeIndexes, HELD_INDEXES, OVER_AIR, RISE_WINDOW_S, SUPPORTS, WALLS};
2943 use crate::toolpath::ExtrusionKind;
2944
2945 #[test]
2949 fn the_plans_type_names_map_to_the_kinds_the_toolpath_draws() {
2950 for name in WALLS {
2951 assert_eq!(ExtrusionKind::of_type(name), ExtrusionKind::Wall, "{name}");
2952 }
2953 for name in SUPPORTS {
2954 assert_eq!(
2955 ExtrusionKind::of_type(name),
2956 ExtrusionKind::Support,
2957 "{name}"
2958 );
2959 }
2960 for name in OVER_AIR {
2961 assert!(
2962 matches!(
2963 ExtrusionKind::of_type(name),
2964 ExtrusionKind::Bridge | ExtrusionKind::Overhang
2965 ),
2966 "{name}"
2967 );
2968 }
2969 }
2970 use printobserver_types::{PrintId, Timestamp};
2971
2972 fn after(start: Timestamp, seconds: i64) -> Timestamp {
2974 start.plus_seconds(seconds).expect("an instant")
2975 }
2976
2977 fn held(indexes: &GcodeIndexes, print_id: PrintId) -> Vec<(Timestamp, i64)> {
2979 indexes
2980 .looked
2981 .lock()
2982 .expect("the looks are held")
2983 .get(&print_id)
2984 .cloned()
2985 .unwrap_or_default()
2986 }
2987
2988 #[test]
2991 fn the_newest_aged_look_is_kept_and_every_older_one_let_go() {
2992 let indexes = GcodeIndexes::default();
2993 let print = PrintId::new();
2994 let start = Timestamp::now();
2995 indexes.note_look(print, start, 10, start);
2996 indexes.note_look(print, after(start, 60), 20, after(start, 60));
2997 let now = after(start, 60 + RISE_WINDOW_S + 30);
2998 indexes.note_look(print, now, 30, now);
2999
3000 assert_eq!(
3001 held(&indexes, print),
3002 vec![(after(start, 60), 20), (now, 30)]
3003 );
3004 assert_eq!(
3005 indexes.newest_look_until(print, after(now, -RISE_WINDOW_S)),
3006 Some((after(start, 60), 20))
3007 );
3008 assert_eq!(indexes.newest_look_until(print, after(start, 30)), None);
3009 }
3010
3011 #[test]
3014 fn the_looks_of_prints_beyond_the_held_count_are_let_go_oldest_first() {
3015 let indexes = GcodeIndexes::default();
3016 let now = Timestamp::now();
3017 let mut prints: Vec<PrintId> = (0..=HELD_INDEXES).map(|_| PrintId::new()).collect();
3018 prints.sort_unstable();
3019 for print in &prints {
3020 indexes.note_look(*print, now, 1, now);
3021 }
3022
3023 assert!(held(&indexes, prints[0]).is_empty());
3024 for print in &prints[1..] {
3025 assert_eq!(held(&indexes, *print), vec![(now, 1)]);
3026 }
3027 }
3028}