1use core::future::Future;
78use core::ops::ControlFlow;
79use core::pin::Pin;
80use core::task::{Context, Poll, Waker};
81use std::collections::BTreeMap;
82use std::sync::{Arc, Mutex, PoisonError};
83
84use printobserver_printer_api::GcodeSink;
85use printobserver_types::contract::Sample;
86use printobserver_types::schemars::JsonSchema;
87use printobserver_types::serde::{Deserialize, Serialize};
88use printobserver_types::{PrintId, Timestamp};
89
90use crate::toolpath::{
91 ExtrusionKind, LayerRef, LayerToolpath, ObjectOutline, Reach, SpoolError, ToolpathSegment,
92};
93
94const LINE_LIMIT: usize = 4096;
99
100const TYPE_LIMIT: usize = 64;
103
104const RISE_WINDOW_S: i64 = 30 * 60;
107
108const LAYERS_SHOWN_BELOW: usize = 5;
111
112const FLOW_WELL_UNDER_ONE: f64 = 0.9;
114
115const OVER_AIR: [&str; 2] = ["Bridge infill", "Overhang perimeter"];
117
118const SUPPORTS: [&str; 2] = ["Support material", "Support material interface"];
120
121const WALLS: [&str; 2] = ["Perimeter", "External perimeter"];
123
124const OBJECT_LIMIT: usize = 1024;
126
127const AXIS_LIMIT: f64 = 1e4;
130
131const WORD_LIMIT: f64 = 1e7;
134
135const WORD_COUNT: usize = 8;
137
138const TRAVEL_MM: f64 = 1e-6;
140
141const NOT_THE_PART: &str = "Custom";
143
144const FAN_FULL: f64 = 255.0;
146
147const CHORD_MM: f64 = 0.5;
149
150pub const PLANNED_CHANGE_REACH_BYTES: u64 = 4096;
159
160const CHANGE_LIMIT: usize = 1024;
163
164#[derive(Debug, Clone, Copy, PartialEq)]
167struct Head {
168 at: [f64; 3],
170 e: f64,
172 axes: Positioning,
174 extruder: Positioning,
176 current_type: Option<usize>,
178}
179
180#[derive(Debug, Clone, PartialEq)]
182struct Layer {
183 begins: u64,
185 at: u64,
187 head: Head,
189 z_mm: Option<f64>,
191 types: u64,
194}
195
196#[derive(Debug, Clone, Copy, PartialEq)]
198struct Mark<T> {
199 at: u64,
201 value: T,
203}
204
205#[derive(Debug, Clone, Default, PartialEq)]
207struct ObjectDraft {
208 bounds: Option<[f64; 4]>,
210 reach: Reach,
212}
213
214#[derive(Debug, Clone, PartialEq)]
216pub struct GcodeIndex {
217 bytes: u64,
219 lines: u64,
221 layers: Vec<Layer>,
223 type_names: Vec<String>,
225 labelled_types: bool,
227 time_left: Vec<Mark<i64>>,
229 flow: Vec<Mark<f64>>,
231 fan: Vec<Mark<f64>>,
233 objects: Vec<BedArea>,
235 labelled_objects: bool,
237 outlines: Vec<ObjectOutline>,
240 blocks: Vec<(u64, Option<usize>)>,
243 spool: Option<std::path::PathBuf>,
245 changes: Vec<ChangeMark>,
247 change_minutes: Vec<Mark<i64>>,
249 first_colour: Option<String>,
251 extruded_mm: f64,
253}
254
255#[derive(Debug, Clone, PartialEq)]
257struct ChangeMark {
258 change: PlannedChange,
260 at: u64,
262 fed_before_mm: f64,
264}
265
266#[derive(Debug, Clone, Copy, PartialEq)]
269pub struct SetInFile {
270 pub value: f64,
272 pub at: u64,
274}
275
276impl GcodeIndex {
277 #[must_use]
279 pub const fn bytes(&self) -> u64 {
280 self.bytes
281 }
282
283 #[must_use]
285 pub const fn lines(&self) -> u64 {
286 self.lines
287 }
288
289 #[must_use]
291 pub const fn layer_count(&self) -> usize {
292 self.layers.len()
293 }
294
295 #[must_use]
298 pub const fn entries(&self) -> usize {
299 self.layers.len()
300 + self.time_left.len()
301 + self.flow.len()
302 + self.fan.len()
303 + self.objects.len()
304 + self.changes.len()
305 + self.change_minutes.len()
306 }
307
308 #[must_use]
311 pub fn resident_bytes(&self) -> usize {
312 let names: usize = self.type_names.iter().map(String::capacity).sum();
313 core::mem::size_of::<Self>()
314 + self.layers.capacity() * core::mem::size_of::<Layer>()
315 + self.type_names.capacity() * core::mem::size_of::<String>()
316 + names
317 + self.time_left.capacity() * core::mem::size_of::<Mark<i64>>()
318 + self.flow.capacity() * core::mem::size_of::<Mark<f64>>()
319 + self.fan.capacity() * core::mem::size_of::<Mark<f64>>()
320 + self.objects.capacity() * core::mem::size_of::<BedArea>()
321 + self.outlines.capacity() * core::mem::size_of::<ObjectOutline>()
322 + self
323 .outlines
324 .iter()
325 .map(|outline| outline.hull_mm.capacity() * core::mem::size_of::<[f32; 2]>())
326 .sum::<usize>()
327 + self.blocks.capacity() * core::mem::size_of::<(u64, Option<usize>)>()
328 + self.changes.capacity() * core::mem::size_of::<ChangeMark>()
329 + self
330 .changes
331 .iter()
332 .filter_map(|mark| mark.change.color.as_ref())
333 .map(String::capacity)
334 .sum::<usize>()
335 + self.change_minutes.capacity() * core::mem::size_of::<Mark<i64>>()
336 + self.first_colour.as_ref().map_or(0, String::capacity)
337 }
338
339 #[must_use]
342 pub fn planned_changes(&self) -> Vec<PlannedChange> {
343 self.changes
344 .iter()
345 .map(|mark| mark.change.clone())
346 .collect()
347 }
348
349 #[must_use]
351 pub fn planned_change(&self, index: u32) -> Option<&PlannedChange> {
352 self.changes
353 .iter()
354 .map(|mark| &mark.change)
355 .find(|change| change.index == index)
356 }
357
358 #[must_use]
361 pub fn planned_segments(&self) -> Vec<PlannedSegment> {
362 if self.changes.is_empty() {
363 return Vec::new();
364 }
365 let colours = core::iter::once(&self.first_colour)
368 .chain(self.changes.iter().map(|mark| &mark.change.color));
369 let fed = core::iter::once(0.0)
370 .chain(self.changes.iter().map(|mark| mark.fed_before_mm))
371 .zip(
372 self.changes
373 .iter()
374 .map(|mark| mark.fed_before_mm)
375 .chain(core::iter::once(self.extruded_mm)),
376 );
377 let segments: Vec<PlannedSegment> = (0_u32..)
378 .zip(colours.zip(fed))
379 .map(|(segment, (colour, (from, to)))| PlannedSegment {
380 segment,
381 color: colour.clone(),
382 filament_mm: millimetres(to - from),
383 })
384 .collect();
385 segments
386 }
387
388 #[must_use]
392 pub fn change_waiting_at(&self, file_position_bytes: u64) -> Option<&PlannedChange> {
393 self.changes
394 .iter()
395 .rev()
396 .map(|mark| &mark.change)
397 .find(|change| change.offset_bytes <= file_position_bytes)
398 .filter(|change| waits_at(change, file_position_bytes))
399 }
400
401 fn changes_read(&self, position: i64) -> usize {
403 u64::try_from(position).map_or(0, |position| {
404 self.changes.partition_point(|mark| mark.at <= position)
405 })
406 }
407
408 #[must_use]
413 pub fn expected_color_at(&self, position: i64) -> Option<String> {
414 if self.changes.is_empty() {
415 return None;
416 }
417 match self.changes_read(position).checked_sub(1) {
418 None => self.first_colour.clone(),
419 Some(last) => self.changes[last].change.color.clone(),
420 }
421 }
422
423 #[must_use]
427 pub fn object_outlines(&self) -> &[ObjectOutline] {
428 &self.outlines
429 }
430
431 #[must_use]
436 pub fn object_at(&self, file_position_bytes: u64) -> Option<usize> {
437 if !self.labelled_objects {
438 return (!self.outlines.is_empty()).then_some(0);
439 }
440 let started = self
441 .blocks
442 .partition_point(|(start, _)| *start <= file_position_bytes);
443 self.blocks[..started]
444 .iter()
445 .rev()
446 .find_map(|(_, outline)| *outline)
447 }
448
449 #[must_use]
451 pub fn layer_at(&self, file_position_bytes: u64) -> Option<LayerRef> {
452 self.layers
453 .iter()
454 .rposition(|layer| layer.at <= file_position_bytes)
455 .map(LayerRef)
456 }
457
458 #[must_use]
460 pub fn layer_z_mm(&self, layer: LayerRef) -> Option<f64> {
461 self.layers.get(layer.0).and_then(|held| held.z_mm)
462 }
463
464 fn lays_object(&self, layer: &Layer) -> bool {
469 layer.types & !self.type_bits(&SUPPORTS) != 0
470 }
471
472 #[must_use]
475 pub fn object_layer_at_or_below(&self, layer: LayerRef) -> Option<LayerRef> {
476 let held = self.layers.get(..=layer.0)?;
477 held.iter()
478 .rposition(|layer| self.lays_object(layer))
479 .map(LayerRef)
480 }
481
482 #[must_use]
485 pub fn first_object_layer(&self) -> Option<(LayerRef, u64)> {
486 let first = self
487 .layers
488 .iter()
489 .position(|layer| self.lays_object(layer))?;
490 Some((LayerRef(first), self.layer_end(first)))
491 }
492
493 fn layer_end(&self, index: usize) -> u64 {
495 self.layers
496 .get(index + 1)
497 .map_or(self.bytes, |next| next.begins)
498 }
499
500 pub fn layer_toolpath(&self, layer: LayerRef) -> Result<LayerToolpath, SpoolError> {
509 use std::io::{Read as _, Seek as _, SeekFrom};
510
511 let held = self.layers.get(layer.0).ok_or(SpoolError::UnknownLayer)?;
512 let path = self.spool.as_ref().ok_or(SpoolError::NoSpool)?;
513 let io = |error: std::io::Error| SpoolError::Io {
514 detail: error.to_string(),
515 };
516 let length =
517 usize::try_from(self.layer_end(layer.0).saturating_sub(held.at)).map_err(|_| {
518 SpoolError::Io {
519 detail: "a layer too long to hold".to_owned(),
520 }
521 })?;
522 let mut file = std::fs::File::open(path).map_err(io)?;
523 file.seek(SeekFrom::Start(held.at)).map_err(io)?;
524 let mut bytes = vec![0; length];
525 file.read_exact(&mut bytes).map_err(io)?;
526 let mut builder = IndexBuilder::reading_layer(self.type_names.clone(), held.head);
527 let _ = builder.take(&bytes);
528 if !builder.line.is_empty() {
529 builder.end_line();
530 }
531 #[expect(
532 clippy::cast_possible_truncation,
533 reason = "a layer height is a few hundred millimetres at most"
534 )]
535 let z_mm = held.z_mm.unwrap_or(0.0) as f32;
536 Ok(LayerToolpath {
537 z_mm,
538 segments: builder.collected.unwrap_or_default(),
539 })
540 }
541
542 pub fn planned_head_at(
552 &self,
553 file_position_bytes: u64,
554 ) -> Result<Option<[f64; 2]>, SpoolError> {
555 use std::io::{Read as _, Seek as _, SeekFrom};
556
557 let Some(layer) = self.layer_at(file_position_bytes) else {
558 return Ok(None);
559 };
560 let held = &self.layers[layer.0];
561 let path = self.spool.as_ref().ok_or(SpoolError::NoSpool)?;
562 let io = |error: std::io::Error| SpoolError::Io {
563 detail: error.to_string(),
564 };
565 let end = file_position_bytes.min(self.layer_end(layer.0));
566 let length = usize::try_from(end.saturating_sub(held.at)).map_err(|_| SpoolError::Io {
567 detail: "a layer too long to hold".to_owned(),
568 })?;
569 let mut file = std::fs::File::open(path).map_err(io)?;
570 file.seek(SeekFrom::Start(held.at)).map_err(io)?;
571 let mut bytes = vec![0; length];
572 file.read_exact(&mut bytes).map_err(io)?;
573 let mut builder = IndexBuilder::reading_layer(self.type_names.clone(), held.head);
574 let _ = builder.take(&bytes);
577 let [x, y, _] = builder.at;
578 Ok(Some([x, y]))
579 }
580
581 #[must_use]
585 pub fn busiest_layer(&self) -> Option<(usize, i64)> {
586 self.layers
587 .iter()
588 .map(|layer| {
589 (
590 usize::try_from(layer.types.count_ones()).unwrap_or(usize::MAX),
591 i64::try_from(layer.at).unwrap_or(i64::MAX),
592 )
593 })
594 .reduce(|best, next| if next.0 > best.0 { next } else { best })
595 }
596
597 #[must_use]
599 pub fn flow_at(&self, position: i64) -> Option<SetInFile> {
600 last_at(&self.flow, position).map(|mark| SetInFile {
601 value: mark.value,
602 at: mark.at,
603 })
604 }
605
606 #[must_use]
609 pub fn fan_at(&self, position: i64) -> Option<SetInFile> {
610 last_at(&self.fan, position).map(|mark| SetInFile {
611 value: mark.value,
612 at: mark.at,
613 })
614 }
615
616 #[must_use]
619 pub fn plan_at(&self, position: i64) -> SlicerPlan {
620 self.plan_with(position, None, None)
621 }
622
623 #[must_use]
627 pub fn plan_with(
628 &self,
629 position: i64,
630 flow_changed: Option<f64>,
631 fan_changed: Option<f64>,
632 ) -> SlicerPlan {
633 let mut unknown = Vec::new();
634 let layer_index = self
635 .layers
636 .iter()
637 .rposition(|layer| reached(layer.at, position));
638 let final_z_mm = self.layers.last().and_then(|layer| layer.z_mm);
639 if self.layers.is_empty() {
640 unknown.push(PlanFact::Layer);
641 }
642 if final_z_mm.is_none() {
643 unknown.push(PlanFact::FinalZ);
644 }
645 if !self.labelled_types {
646 unknown.push(PlanFact::Types);
647 }
648 let types = layer_index.map_or_else(Vec::new, |index| {
649 let bits = self.layers[index].types;
650 self.type_names
651 .iter()
652 .enumerate()
653 .filter(|(bit, _)| bits & (1 << bit) != 0)
654 .map(|(_, name)| name.clone())
655 .collect()
656 });
657 let minutes_left = last_at(&self.time_left, position).map(|mark| mark.value);
658 if minutes_left.is_none() {
659 unknown.push(PlanFact::MinutesLeft);
660 }
661 let flow_factor = set_value(
662 self.flow_at(position).map(|set| set.value),
663 flow_changed,
664 PlanFact::FlowFactor,
665 &mut unknown,
666 );
667 let fan_percent = set_value(
668 self.fan_at(position).map(|set| set.value),
669 fan_changed,
670 PlanFact::FanPercent,
671 &mut unknown,
672 );
673 if !self.labelled_objects {
674 unknown.push(PlanFact::Objects);
675 }
676 unknown.sort_unstable();
677 let in_force =
678 |set: &Option<SetValue>| set.as_ref().and_then(|set| set.changed.or(set.file));
679 let mut at_odds = Vec::new();
680 if let Some(index) = layer_index {
681 let shown = self.layers[index.saturating_sub(LAYERS_SHOWN_BELOW)..=index]
682 .iter()
683 .fold(0, |bits, layer| bits | layer.types);
684 if in_force(&fan_percent).is_some_and(|fan| fan <= 0.0)
685 && shown & self.type_bits(&OVER_AIR) != 0
686 {
687 at_odds.push(PlanMismatch::FanOffOverBridges);
688 }
689 if in_force(&flow_factor).is_some_and(|flow| flow < FLOW_WELL_UNDER_ONE)
690 && self.layers[index].types & self.type_bits(&WALLS) != 0
691 {
692 at_odds.push(PlanMismatch::FlowLowOverWalls);
693 }
694 }
695 let next_change = self
696 .changes
697 .get(self.changes_read(position))
698 .map(|mark| mark.change.clone());
699 let minutes_to_next_change = next_change
700 .as_ref()
701 .and_then(|_| last_at(&self.change_minutes, position))
702 .map(|mark| mark.value);
703 SlicerPlan {
704 expected_color: self.expected_color_at(position),
705 next_change,
706 minutes_to_next_change,
707 change_waiting: None,
708 layer: layer_index.map(|index| index + 1),
709 z_mm: layer_index.and_then(|index| self.layers[index].z_mm),
710 final_z_mm,
711 types,
712 minutes_left,
713 flow_factor,
714 fan_percent,
715 object_count: self.labelled_objects.then_some(self.objects.len()),
716 objects: self.objects.clone(),
717 rise: None,
718 at_odds,
719 unknown,
720 }
721 }
722
723 fn type_bits(&self, names: &[&str]) -> u64 {
725 self.type_names
726 .iter()
727 .enumerate()
728 .filter(|(_, name)| names.contains(&name.as_str()))
729 .fold(0, |bits, (bit, _)| bits | (1 << bit))
730 }
731
732 #[must_use]
741 pub fn risen_since(&self, earlier: i64, now: i64) -> Option<f64> {
742 self.height_and_rise_since(earlier, now)
743 .map(|[_, risen]| risen)
744 }
745
746 #[must_use]
750 pub fn height_and_rise_since(&self, earlier: i64, now: i64) -> Option<[f64; 2]> {
751 let at = |position| {
752 self.layers
753 .iter()
754 .rposition(|layer| reached(layer.at, position))
755 .filter(|index| self.layers[*index].z_mm.is_some())
756 };
757 let (then, now) = (at(earlier)?, at(now)?);
758 let supports = self.type_bits(&SUPPORTS);
759 let lays_the_part = |layer: &&Layer| layer.types & !supports != 0;
760 let mut top = self.layers[..=then]
763 .iter()
764 .rev()
765 .filter(lays_the_part)
766 .find_map(|layer| layer.z_mm)
767 .or(self.layers[then].z_mm)?;
768 let height = top;
769 let mut risen = 0.0;
770 for layer in self
771 .layers
772 .iter()
773 .take(now + 1)
774 .skip(then + 1)
775 .filter(lays_the_part)
776 {
777 let Some(z) = layer.z_mm else { continue };
778 risen += (z - top).max(0.0);
779 top = top.max(z);
780 }
781 let tenth = |mm: f64| (mm * 10.0).round() / 10.0;
782 Some([tenth(height), tenth(risen)])
783 }
784}
785
786fn set_value(
789 file: Option<f64>,
790 changed: Option<f64>,
791 fact: PlanFact,
792 unknown: &mut Vec<PlanFact>,
793) -> Option<SetValue> {
794 if file.is_none() {
795 unknown.push(fact);
796 }
797 (file.is_some() || changed.is_some()).then_some(SetValue { file, changed })
798}
799
800const fn waits_at(change: &PlannedChange, position: u64) -> bool {
802 position >= change.offset_bytes && position - change.offset_bytes <= PLANNED_CHANGE_REACH_BYTES
803}
804
805fn millimetres(length: f64) -> f64 {
807 (length.max(0.0) * 1000.0).round() / 1000.0
808}
809
810fn reached(at: u64, position: i64) -> bool {
812 u64::try_from(position).is_ok_and(|position| at <= position)
813}
814
815fn last_at<T: Copy>(marks: &[Mark<T>], position: i64) -> Option<Mark<T>> {
817 let Ok(position) = u64::try_from(position) else {
818 return None;
819 };
820 let reached = marks.partition_point(|mark| mark.at <= position);
821 reached.checked_sub(1).map(|index| marks[index])
822}
823
824#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
827#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
828#[schemars(crate = "printobserver_types::schemars")]
829pub struct SetValue {
830 #[serde(default, skip_serializing_if = "Option::is_none")]
832 pub file: Option<f64>,
833 #[serde(default, skip_serializing_if = "Option::is_none")]
836 pub changed: Option<f64>,
837}
838
839pub type BedArea = [i64; 4];
844
845#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
848#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
849#[schemars(crate = "printobserver_types::schemars")]
850pub struct Rise {
851 pub since: Timestamp,
856 pub mm: [f64; 2],
862}
863
864pub(crate) fn null_is_sent(schema: &mut printobserver_types::schemars::Schema) {
872 use printobserver_types::serde_json::Value;
873 if let Some(Value::Object(properties)) = schema.get_mut("properties") {
874 for property in properties.values_mut() {
875 if property.get("properties").is_some()
876 && let Ok(inline) =
877 printobserver_types::schemars::Schema::try_from(core::mem::take(property))
878 {
879 let mut inline = inline;
880 null_is_sent(&mut inline);
881 *property = inline.to_value();
882 }
883 }
884 }
885 let nullable = |property: &Value| match property.get("type") {
886 Some(Value::Array(types)) => types.iter().any(|named| named == "null"),
887 _ => property
888 .get("anyOf")
889 .and_then(Value::as_array)
890 .is_some_and(|arms| {
891 arms.iter()
892 .any(|arm| arm.get("type") == Some(&Value::from("null")))
893 }),
894 };
895 let sent: Vec<Value> = schema
896 .get("properties")
897 .and_then(Value::as_object)
898 .map(|properties| {
899 properties
900 .iter()
901 .filter(|(_, property)| nullable(property))
902 .map(|(name, _)| Value::from(name.as_str()))
903 .collect()
904 })
905 .unwrap_or_default();
906 if sent.is_empty() {
907 return;
908 }
909 let required = schema
910 .ensure_object()
911 .entry("required")
912 .or_insert_with(|| Value::Array(Vec::new()));
913 if let Value::Array(required) = required {
914 for name in sent {
915 if !required.contains(&name) {
916 required.push(name);
917 }
918 }
919 }
920}
921
922#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
924#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
925#[schemars(crate = "printobserver_types::schemars")]
926pub enum PlannedChangeKind {
927 ColorChange,
929 Pause,
931}
932
933#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
936#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
937#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
938pub struct PlannedChange {
939 pub index: u32,
941 pub kind: PlannedChangeKind,
943 pub offset_bytes: u64,
945 pub layer: u32,
948 pub z_mm: f64,
950 pub color: Option<String>,
954}
955
956#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
958#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
959#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
960pub struct PlannedSegment {
961 pub segment: u32,
964 pub color: Option<String>,
967 pub filament_mm: f64,
969}
970
971#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
973#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
974#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
975pub struct PlannedChanges {
976 pub changes: Vec<PlannedChange>,
978 pub segments: Vec<PlannedSegment>,
980 pub waiting: Option<u32>,
983 pub expected_color: Option<String>,
986}
987
988impl Sample for PlannedChange {
989 fn sample_full() -> Self {
990 Self {
991 index: 0,
992 kind: PlannedChangeKind::ColorChange,
993 offset_bytes: 48_213,
994 layer: 12,
995 z_mm: 2.4,
996 color: Some("#FF0000".to_owned()),
997 }
998 }
999
1000 fn sample_alternates() -> Vec<Self> {
1001 vec![Self {
1002 index: 1,
1003 kind: PlannedChangeKind::Pause,
1004 offset_bytes: 96_410,
1005 layer: 24,
1006 z_mm: 4.8,
1007 color: None,
1008 }]
1009 }
1010}
1011
1012impl Sample for PlannedSegment {
1013 fn sample_full() -> Self {
1014 Self {
1015 segment: 1,
1016 color: Some("#FF0000".to_owned()),
1017 filament_mm: 812.4,
1018 }
1019 }
1020
1021 fn sample_alternates() -> Vec<Self> {
1022 vec![Self {
1023 segment: 0,
1024 color: None,
1025 filament_mm: 0.0,
1026 }]
1027 }
1028}
1029
1030impl Sample for PlannedChanges {
1031 fn sample_full() -> Self {
1032 Self {
1033 changes: vec![PlannedChange::sample_full()],
1034 segments: vec![
1035 PlannedSegment {
1036 segment: 0,
1037 color: Some("#FFFFFF".to_owned()),
1038 filament_mm: 301.7,
1039 },
1040 PlannedSegment::sample_full(),
1041 ],
1042 waiting: Some(0),
1043 expected_color: Some("#FF0000".to_owned()),
1044 }
1045 }
1046
1047 fn sample_alternates() -> Vec<Self> {
1048 vec![Self {
1049 waiting: None,
1050 expected_color: None,
1051 ..Self::sample_full()
1052 }]
1053 }
1054}
1055
1056#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1059#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1060#[schemars(crate = "printobserver_types::schemars")]
1061pub enum PlanMismatch {
1062 FanOffOverBridges,
1065 FlowLowOverWalls,
1067}
1068
1069#[derive(
1071 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
1072)]
1073#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1074#[schemars(crate = "printobserver_types::schemars")]
1075pub enum PlanFact {
1076 Layer,
1078 FinalZ,
1080 Types,
1082 MinutesLeft,
1084 FlowFactor,
1086 FanPercent,
1088 Objects,
1090 Rise,
1094}
1095
1096#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1103#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1104#[schemars(crate = "printobserver_types::schemars")]
1105pub struct SlicerPlan {
1106 #[serde(default, skip_serializing_if = "Option::is_none")]
1110 pub expected_color: Option<String>,
1111 #[serde(default, skip_serializing_if = "Option::is_none")]
1114 pub next_change: Option<PlannedChange>,
1115 #[serde(default, skip_serializing_if = "Option::is_none")]
1119 pub minutes_to_next_change: Option<i64>,
1120 #[serde(default, skip_serializing_if = "Option::is_none")]
1123 pub change_waiting: Option<PlannedChange>,
1124 #[serde(default, skip_serializing_if = "Option::is_none")]
1127 pub layer: Option<usize>,
1128 #[serde(default, skip_serializing_if = "Option::is_none")]
1130 pub z_mm: Option<f64>,
1131 #[serde(default, skip_serializing_if = "Option::is_none")]
1133 pub final_z_mm: Option<f64>,
1134 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1137 pub types: Vec<String>,
1138 #[serde(default, skip_serializing_if = "Option::is_none")]
1140 pub minutes_left: Option<i64>,
1141 #[serde(default, skip_serializing_if = "Option::is_none")]
1143 pub flow_factor: Option<SetValue>,
1144 #[serde(default, skip_serializing_if = "Option::is_none")]
1146 pub fan_percent: Option<SetValue>,
1147 #[serde(default, skip_serializing_if = "Option::is_none")]
1149 pub object_count: Option<usize>,
1150 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1154 pub objects: Vec<BedArea>,
1155 #[serde(default, skip_serializing_if = "Option::is_none")]
1158 pub rise: Option<Rise>,
1159 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1161 pub at_odds: Vec<PlanMismatch>,
1162 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1165 pub unknown: Vec<PlanFact>,
1166}
1167
1168impl Sample for SlicerPlan {
1169 fn sample_full() -> Self {
1170 Self {
1171 expected_color: Some("#FF0000".to_owned()),
1172 next_change: Some(PlannedChange::sample_full()),
1173 minutes_to_next_change: Some(17),
1174 change_waiting: Some(PlannedChange::sample_full()),
1175 layer: Some(12),
1176 z_mm: Some(2.4),
1177 types: vec![
1178 "Perimeter".to_owned(),
1179 "External perimeter".to_owned(),
1180 "Support material".to_owned(),
1181 ],
1182 final_z_mm: Some(30.0),
1183 minutes_left: Some(42),
1184 flow_factor: Some(SetValue {
1185 file: Some(1.0),
1186 changed: Some(0.95),
1187 }),
1188 fan_percent: Some(SetValue {
1189 file: Some(100.0),
1190 changed: None,
1191 }),
1192 object_count: Some(1),
1193 objects: vec![[100, 99, 150, 117]],
1194 rise: Some(Rise {
1195 since: Timestamp::sample_full(),
1196 mm: [7.2, 4.8],
1197 }),
1198 at_odds: vec![PlanMismatch::FlowLowOverWalls],
1199 unknown: vec![PlanFact::Objects],
1200 }
1201 }
1202
1203 fn sample_minimal() -> Self {
1204 Self {
1205 expected_color: None,
1206 next_change: None,
1207 minutes_to_next_change: None,
1208 change_waiting: None,
1209 layer: None,
1210 z_mm: None,
1211 final_z_mm: None,
1212 types: Vec::new(),
1213 minutes_left: None,
1214 flow_factor: None,
1215 fan_percent: None,
1216 object_count: None,
1217 objects: Vec::new(),
1218 rise: None,
1219 at_odds: Vec::new(),
1220 unknown: Vec::new(),
1221 }
1222 }
1223}
1224
1225#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1227enum Positioning {
1228 #[default]
1230 Absolute,
1231 Relative,
1233}
1234
1235#[derive(Debug, Default)]
1238pub struct IndexBuilder {
1239 line: Vec<u8>,
1241 overlong: bool,
1243 read: u64,
1245 lines: u64,
1247 layers: Vec<Layer>,
1249 type_names: Vec<String>,
1251 labelled_types: bool,
1253 current_type: Option<usize>,
1255 time_left: Vec<Mark<i64>>,
1257 flow: Vec<Mark<f64>>,
1259 fan: Vec<Mark<f64>>,
1261 objects: Vec<ObjectDraft>,
1263 object_numbers: BTreeMap<i64, usize>,
1265 current_object: Option<usize>,
1268 labelled_objects: bool,
1270 at: [f64; 3],
1272 e: f64,
1274 axes: Positioning,
1276 extruder: Positioning,
1278 line_began: u64,
1280 all: Reach,
1282 blocks: Vec<(u64, usize)>,
1285 spool: Option<Spooling>,
1287 collected: Option<Vec<ToolpathSegment>>,
1289 reached_last: Option<[f64; 2]>,
1291 changes: Vec<ChangeDraft>,
1293 change_minutes: Vec<Mark<i64>>,
1295 colour_comment: Option<(u64, String)>,
1297 first_colour: Option<String>,
1299 extruded_mm: f64,
1301 laid_in_layers: usize,
1304}
1305
1306#[derive(Debug, Clone, PartialEq)]
1309struct ChangeDraft {
1310 kind: PlannedChangeKind,
1312 offset: u64,
1314 at: u64,
1316 layer: usize,
1319 color: Option<String>,
1321 fed_before_mm: f64,
1323}
1324
1325#[derive(Debug)]
1327struct Spooling {
1328 path: std::path::PathBuf,
1330 writer: std::io::BufWriter<std::fs::File>,
1332 failed: bool,
1334}
1335
1336impl GcodeSink for IndexBuilder {
1337 fn take(&mut self, piece: &[u8]) -> ControlFlow<()> {
1338 if let Some(spool) = self.spool.as_mut().filter(|spool| !spool.failed) {
1348 use std::io::Write as _;
1349 spool.failed = spool.writer.write_all(piece).is_err();
1350 }
1351 let mut start = 0;
1352 let mut at = 0;
1353 while at < piece.len() {
1354 if piece[at] == b'\n' {
1355 let head = &piece[start..at];
1356 self.read += u64::try_from(at + 1 - start).unwrap_or(u64::MAX);
1357 if self.line.is_empty() && !self.overlong {
1358 self.lines += 1;
1360 if head.len() <= LINE_LIMIT {
1361 self.read_line(head);
1362 }
1363 } else {
1364 self.hold(head);
1365 self.end_line();
1366 }
1367 self.line_began = self.read;
1368 start = at + 1;
1369 }
1370 at += 1;
1371 }
1372 let rest = &piece[start..];
1373 self.hold(rest);
1374 self.read += u64::try_from(rest.len()).unwrap_or(u64::MAX);
1375 ControlFlow::Continue(())
1376 }
1377}
1378
1379impl IndexBuilder {
1380 #[must_use]
1382 pub fn new() -> Self {
1383 Self::default()
1384 }
1385
1386 pub fn spooling(path: std::path::PathBuf) -> std::io::Result<Self> {
1394 let file = std::fs::File::create(&path)?;
1395 Ok(Self {
1396 spool: Some(Spooling {
1397 path,
1398 writer: std::io::BufWriter::with_capacity(1 << 16, file),
1399 failed: false,
1400 }),
1401 ..Self::default()
1402 })
1403 }
1404
1405 fn reading_layer(type_names: Vec<String>, head: Head) -> Self {
1408 Self {
1409 type_names,
1410 labelled_types: true,
1411 current_type: head.current_type,
1412 at: head.at,
1413 e: head.e,
1414 axes: head.axes,
1415 extruder: head.extruder,
1416 collected: Some(Vec::new()),
1417 ..Self::default()
1418 }
1419 }
1420
1421 #[must_use]
1424 pub fn finish(mut self) -> GcodeIndex {
1425 if !self.line.is_empty() || self.overlong {
1426 self.end_line();
1427 }
1428 let mut drafts: Vec<Option<ObjectDraft>> = self.objects.into_iter().map(Some).collect();
1429 let mut objects = Vec::new();
1430 let mut outlines = Vec::new();
1431 let mut outline_of = vec![None; drafts.len()];
1432 for place in self.object_numbers.into_values() {
1433 let Some(draft) = drafts.get_mut(place).and_then(Option::take) else {
1434 continue;
1435 };
1436 let Some([least_x, least_y, most_x, most_y]) = draft.bounds else {
1437 continue;
1438 };
1439 objects.push([
1440 whole(tenth(least_x).floor()),
1441 whole(tenth(least_y).floor()),
1442 whole(tenth(most_x).ceil()),
1443 whole(tenth(most_y).ceil()),
1444 ]);
1445 outline_of[place] = Some(outlines.len());
1446 outlines.push(draft.reach.outline().unwrap_or(ObjectOutline {
1447 hull_mm: Vec::new(),
1448 }));
1449 }
1450 if !self.labelled_objects {
1451 outlines.extend(self.all.outline());
1452 }
1453 let blocks = self
1454 .blocks
1455 .into_iter()
1456 .map(|(start, place)| (start, outline_of.get(place).copied().flatten()))
1457 .collect();
1458 let spool = self.spool.and_then(|mut spool| {
1459 use std::io::Write as _;
1460 if spool.failed || spool.writer.flush().is_err() {
1461 drop(spool.writer);
1462 let _ = std::fs::remove_file(&spool.path);
1463 return None;
1464 }
1465 Some(spool.path)
1466 });
1467 let changes = (0_u32..)
1468 .zip(self.changes)
1469 .map(|(index, draft)| {
1470 let layer = draft.layer.min(self.layers.len().saturating_sub(1));
1473 ChangeMark {
1474 change: PlannedChange {
1475 index,
1476 kind: draft.kind,
1477 offset_bytes: draft.offset,
1478 layer: u32::try_from(layer + 1).unwrap_or(u32::MAX),
1479 z_mm: self
1480 .layers
1481 .get(layer)
1482 .and_then(|held| held.z_mm)
1483 .unwrap_or(0.0),
1484 color: draft.color,
1485 },
1486 at: draft.at,
1487 fed_before_mm: draft.fed_before_mm,
1488 }
1489 })
1490 .collect();
1491 GcodeIndex {
1492 bytes: self.read,
1493 lines: self.lines,
1494 changes,
1495 change_minutes: self.change_minutes,
1496 first_colour: self.first_colour,
1497 extruded_mm: self.extruded_mm,
1498 layers: self.layers,
1499 type_names: self.type_names,
1500 labelled_types: self.labelled_types,
1501 time_left: self.time_left,
1502 flow: self.flow,
1503 fan: self.fan,
1504 objects,
1505 labelled_objects: self.labelled_objects,
1506 outlines,
1507 blocks,
1508 spool,
1509 }
1510 }
1511
1512 fn hold(&mut self, bytes: &[u8]) {
1514 if self.overlong {
1515 return;
1516 }
1517 if self.line.len() + bytes.len() > LINE_LIMIT {
1518 self.overlong = true;
1519 self.line.clear();
1520 return;
1521 }
1522 self.line.extend_from_slice(bytes);
1523 }
1524
1525 fn end_line(&mut self) {
1527 self.lines += 1;
1528 let line = core::mem::take(&mut self.line);
1529 if !self.overlong {
1530 self.read_line(&line);
1531 }
1532 self.overlong = false;
1533 self.line = line;
1534 self.line.clear();
1535 }
1536
1537 fn read_line(&mut self, raw: &[u8]) {
1539 let raw = raw.trim_ascii();
1540 if let Some(comment) = raw.strip_prefix(b";") {
1541 if let Ok(comment) = core::str::from_utf8(comment) {
1542 self.comment(comment.trim_end());
1543 }
1544 return;
1545 }
1546 if let [b'G', code @ b'0'..=b'3', b' ', rest @ ..] = raw {
1549 self.motion(u32::from(code - b'0'), &move_of(rest));
1550 return;
1551 }
1552 let held = words(raw);
1553 let mut words = held.as_slice();
1554 if let Some((Word { letter: b'N', .. }, rest)) = words.split_first() {
1556 words = rest;
1557 }
1558 let Some(first) = words.first() else {
1559 return;
1560 };
1561 let code = if held.numbered {
1562 held.second_code
1563 } else {
1564 held.first_code
1565 };
1566 match (char::from(first.letter), code) {
1567 ('G', Some(code @ 0..=3)) => self.motion(code, &Move::of(&words[1..])),
1568 ('G', Some(28)) => self.home(&words[1..]),
1569 ('G', Some(90)) => self.axes = Positioning::Absolute,
1570 ('G', Some(91)) => self.axes = Positioning::Relative,
1571 ('G', Some(92)) => self.declare(&words[1..]),
1572 ('M', Some(82)) => self.extruder = Positioning::Absolute,
1573 ('M', Some(83)) => self.extruder = Positioning::Relative,
1574 ('M', Some(73)) => self.estimate(&words[1..]),
1575 ('M', Some(221)) => self.flow_factor(&words[1..]),
1576 ('M', Some(106)) => self.fan_speed(&words[1..], Fan::Set),
1577 ('M', Some(107)) => self.fan_speed(&words[1..], Fan::Off),
1578 ('M', Some(486)) => self.object(raw, &words[1..]),
1579 ('M', Some(600)) => self.planned(PlannedChangeKind::ColorChange),
1580 ('M', Some(601)) => self.planned(PlannedChangeKind::Pause),
1581 _ => {}
1582 }
1583 }
1584
1585 fn comment(&mut self, comment: &str) {
1587 if comment == "LAYER_CHANGE" {
1588 self.layers.push(Layer {
1589 begins: self.line_began,
1590 head: Head {
1591 at: self.at,
1592 e: self.e,
1593 axes: self.axes,
1594 extruder: self.extruder,
1595 current_type: self.current_type,
1596 },
1597 at: self.read,
1598 z_mm: None,
1599 types: 0,
1600 });
1601 } else if let Some(z) = comment.strip_prefix("Z:") {
1602 if let Some(layer) = self.layers.last_mut()
1603 && layer.z_mm.is_none()
1604 {
1605 layer.z_mm = z
1608 .trim()
1609 .parse::<f64>()
1610 .ok()
1611 .filter(|z| (0.0..=AXIS_LIMIT).contains(z));
1612 }
1613 } else if let Some(change) = comment.strip_prefix("COLOR_CHANGE,") {
1614 self.colour_comment = change
1616 .split(',')
1617 .nth(1)
1618 .and_then(colour_of)
1619 .map(|colour| (self.lines, colour));
1620 } else if let Some(colours) = comment.trim_start().strip_prefix("filament_colour = ") {
1621 if self.first_colour.is_none() {
1622 self.first_colour = colours.split(';').next().and_then(colour_of);
1623 }
1624 } else if let Some(name) = comment.strip_prefix("TYPE:") {
1625 let name = name.trim();
1626 self.labelled_types = true;
1627 self.current_type = if name == NOT_THE_PART {
1628 None
1629 } else {
1630 self.intern(name)
1631 };
1632 }
1633 }
1634
1635 fn intern(&mut self, name: &str) -> Option<usize> {
1637 if let Some(bit) = self.type_names.iter().position(|held| held == name) {
1638 return Some(bit);
1639 }
1640 if self.type_names.len() >= TYPE_LIMIT {
1641 return None;
1642 }
1643 self.type_names.push(name.to_owned());
1644 Some(self.type_names.len() - 1)
1645 }
1646
1647 fn motion(&mut self, code: u32, words: &Move) {
1649 let start = self.at;
1652 let relative = self.axes == Positioning::Relative;
1653 if let Some(x) = words.x {
1654 self.place(0, x, relative);
1655 }
1656 if let Some(y) = words.y {
1657 self.place(1, y, relative);
1658 }
1659 if let Some(z) = words.z {
1660 self.place(2, z, relative);
1661 }
1662 let mut fed = 0.0;
1663 if let Some(value) = words.e {
1664 if relative || self.extruder == Positioning::Relative {
1665 self.e += value;
1666 fed = value;
1667 } else {
1668 fed = value - self.e;
1669 self.e = value;
1670 }
1671 }
1672 let travel = (self.at[0] - start[0]).hypot(self.at[1] - start[1]);
1673 self.extruded_mm += fed;
1674 if fed <= 0.0 || (travel <= TRAVEL_MM && code < 2) {
1675 return;
1676 }
1677 self.laid_in_layers = self.layers.len();
1678 if let (Some(layer), Some(bit)) = (self.layers.last_mut(), self.current_type) {
1679 layer.types |= 1 << bit;
1680 }
1681 let end = self.at;
1682 let turn = match code {
1683 2 => Some(Turn::Clockwise),
1684 3 => Some(Turn::CounterClockwise),
1685 _ => None,
1686 };
1687 let arc = turn.and_then(|turn| arc_of(words, turn, start, end));
1688 if let Some(collected) = self.collected.as_mut() {
1689 let kind = self
1690 .current_type
1691 .and_then(|bit| self.type_names.get(bit))
1692 .map_or(ExtrusionKind::Other, |name| ExtrusionKind::of_type(name));
1693 collect_segments(collected, kind, start, end, arc);
1694 return;
1695 }
1696 let part_of_plan = !(self.labelled_types && self.current_type.is_none());
1697 let reach = if let Some(object) = self.current_object {
1698 let draft = &mut self.objects[object];
1699 grow(&mut draft.bounds, start[0], start[1]);
1700 grow(&mut draft.bounds, end[0], end[1]);
1701 if let Some(turn) = turn {
1702 for [x, y] in arc_extremes(words, turn, start, end) {
1703 grow(&mut draft.bounds, x, y);
1704 }
1705 }
1706 &mut draft.reach
1707 } else if !self.labelled_objects && part_of_plan {
1708 &mut self.all
1709 } else {
1710 return;
1711 };
1712 if self.reached_last != Some([start[0], start[1]]) {
1715 reach.point(start[0], start[1]);
1716 }
1717 reach.point(end[0], end[1]);
1718 self.reached_last = Some([end[0], end[1]]);
1719 if let Some(arc) = arc {
1720 reach.arc(arc.centre, arc.radius, arc.base, arc.sweep);
1721 }
1722 }
1723
1724 fn place(&mut self, axis: usize, value: f64, relative: bool) {
1728 let landed = if relative {
1729 self.at[axis] + value
1730 } else {
1731 value
1732 };
1733 if landed.abs() <= AXIS_LIMIT {
1734 self.at[axis] = landed;
1735 }
1736 }
1737
1738 fn home(&mut self, words: &[Word]) {
1740 let named: Vec<usize> = ['X', 'Y', 'Z']
1741 .into_iter()
1742 .enumerate()
1743 .filter(|(_, letter)| words.iter().any(|word| char::from(word.letter) == *letter))
1744 .map(|(axis, _)| axis)
1745 .collect();
1746 if named.is_empty() {
1747 self.at = [0.0; 3];
1748 } else {
1749 for axis in named {
1750 self.at[axis] = 0.0;
1751 }
1752 }
1753 }
1754
1755 fn declare(&mut self, words: &[Word]) {
1758 if words.is_empty() {
1759 self.at = [0.0; 3];
1760 self.e = 0.0;
1761 return;
1762 }
1763 for (axis, letter) in ['X', 'Y', 'Z'].into_iter().enumerate() {
1764 if let Some(value) = number(words, letter).filter(|value| value.abs() <= AXIS_LIMIT) {
1765 self.at[axis] = value;
1766 }
1767 }
1768 if let Some(value) = number(words, 'E') {
1769 self.e = value;
1770 }
1771 }
1772
1773 fn estimate(&mut self, words: &[Word]) {
1776 if let Some(minutes) = number(words, 'C').filter(|minutes| *minutes >= 0.0) {
1777 self.change_minutes.push(Mark {
1778 at: self.read,
1779 value: whole(minutes),
1780 });
1781 }
1782 if number(words, 'P').is_none() {
1783 return;
1784 }
1785 if let Some(minutes) = number(words, 'R').filter(|minutes| *minutes >= 0.0) {
1786 self.time_left.push(Mark {
1787 at: self.read,
1788 value: whole(minutes),
1789 });
1790 }
1791 }
1792
1793 fn planned(&mut self, kind: PlannedChangeKind) {
1796 let named = self.colour_comment.take();
1797 if self.changes.len() >= CHANGE_LIMIT {
1798 return;
1799 }
1800 let color = match kind {
1801 PlannedChangeKind::ColorChange => named
1802 .filter(|(line, _)| line + 1 == self.lines)
1803 .map(|(_, colour)| colour),
1804 PlannedChangeKind::Pause => None,
1805 };
1806 let layer = if self.laid_in_layers == self.layers.len() {
1807 self.layers.len()
1808 } else {
1809 self.layers.len() - 1
1810 };
1811 self.changes.push(ChangeDraft {
1812 kind,
1813 offset: self.line_began,
1814 at: self.read,
1815 layer,
1816 color,
1817 fed_before_mm: self.extruded_mm,
1818 });
1819 }
1820
1821 fn flow_factor(&mut self, words: &[Word]) {
1823 if let Some(percent) = number(words, 'S').filter(|percent| *percent >= 0.0) {
1824 mark_setting(&mut self.flow, self.read, percent / 100.0);
1825 }
1826 }
1827
1828 fn fan_speed(&mut self, words: &[Word], command: Fan) {
1830 if number(words, 'P').is_some_and(|fan| fan != 0.0) {
1831 return;
1832 }
1833 let speed = match command {
1834 Fan::Off => 0.0,
1835 Fan::Set => number(words, 'S').unwrap_or(FAN_FULL),
1836 };
1837 let percent = (speed.clamp(0.0, FAN_FULL) / FAN_FULL * 100.0).round();
1838 mark_setting(&mut self.fan, self.read, percent);
1839 }
1840
1841 fn object(&mut self, raw: &[u8], words: &[Word]) {
1843 if raw
1846 .strip_prefix(b"M486")
1847 .is_some_and(|rest| rest.trim_ascii_start().starts_with(b"A"))
1848 {
1849 self.labelled_objects = true;
1850 return;
1851 }
1852 let Some(number) = number(words, 'S')
1855 .filter(|number| (number - number.round()).abs() < f64::EPSILON && *number >= -1.0)
1856 else {
1857 return;
1858 };
1859 self.labelled_objects = true;
1860 if number < 0.0 {
1861 self.current_object = None;
1862 self.reached_last = None;
1863 return;
1864 }
1865 let id = whole(number);
1866 let place = if let Some(place) = self.object_numbers.get(&id) {
1867 *place
1868 } else if self.objects.len() >= OBJECT_LIMIT {
1869 self.current_object = None;
1870 self.reached_last = None;
1871 return;
1872 } else {
1873 self.objects.push(ObjectDraft::default());
1874 self.object_numbers.insert(id, self.objects.len() - 1);
1875 self.objects.len() - 1
1876 };
1877 self.current_object = Some(place);
1878 self.reached_last = None;
1879 self.blocks.push((self.read, place));
1880 }
1881}
1882
1883fn colour_of(text: &str) -> Option<String> {
1885 let text = text.trim();
1886 let hex = text.strip_prefix('#')?;
1887 (hex.len() == 6 && hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
1888 .then(|| text.to_ascii_uppercase())
1889}
1890
1891fn mark_setting(marks: &mut Vec<Mark<f64>>, at: u64, value: f64) {
1895 marks.push(Mark { at, value });
1896}
1897
1898fn whole(value: f64) -> i64 {
1901 format!("{:.0}", value.round()).parse().unwrap_or_default()
1902}
1903
1904fn tenth(value: f64) -> f64 {
1908 (value * 10.0).round() / 10.0
1909}
1910
1911fn grow(bounds: &mut Option<[f64; 4]>, x: f64, y: f64) {
1913 *bounds = Some(match *bounds {
1914 None => [x, y, x, y],
1915 Some([least_x, least_y, most_x, most_y]) => {
1916 [least_x.min(x), least_y.min(y), most_x.max(x), most_y.max(y)]
1917 }
1918 });
1919}
1920
1921#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1923enum Turn {
1924 Clockwise,
1926 CounterClockwise,
1928}
1929
1930#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1933enum Fan {
1934 Set,
1936 Off,
1938}
1939
1940fn arc_extremes(
1949 words: &Move,
1950 turn: Turn,
1951 start: [f64; 3],
1952 end: [f64; 3],
1953) -> impl Iterator<Item = [f64; 2]> {
1954 let reach = arc_of(words, turn, start, end).map(|arc| {
1955 let ArcGeometry {
1956 centre,
1957 radius,
1958 base,
1959 sweep,
1960 ..
1961 } = arc;
1962 let tau = core::f64::consts::TAU;
1963 (0..4).filter_map(move |quarter| {
1964 let angle = core::f64::consts::FRAC_PI_2 * f64::from(quarter);
1965 ((angle - base).rem_euclid(tau) <= sweep + 1e-9).then(|| {
1966 [
1967 centre[0] + radius * angle.cos(),
1968 centre[1] + radius * angle.sin(),
1969 ]
1970 })
1971 })
1972 });
1973 reach.into_iter().flatten()
1974}
1975
1976#[derive(Debug, Clone, Copy)]
1978struct ArcGeometry {
1979 centre: [f64; 2],
1981 radius: f64,
1983 base: f64,
1986 sweep: f64,
1989 turn: Turn,
1991}
1992
1993fn arc_of(words: &Move, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<ArcGeometry> {
1997 let centre = words.r.map_or_else(
1998 || {
1999 Some([
2000 start[0] + words.i.unwrap_or(0.0),
2001 start[1] + words.j.unwrap_or(0.0),
2002 ])
2003 },
2004 |radius| centre_of_radius(radius, turn, start, end),
2005 )?;
2006 let radius = (start[0] - centre[0]).hypot(start[1] - centre[1]);
2007 let from = (start[1] - centre[1]).atan2(start[0] - centre[0]);
2008 let to = (end[1] - centre[1]).atan2(end[0] - centre[0]);
2009 let tau = core::f64::consts::TAU;
2010 let (base, sweep) = match turn {
2013 Turn::Clockwise => (to, (from - to).rem_euclid(tau)),
2014 Turn::CounterClockwise => (from, (to - from).rem_euclid(tau)),
2015 };
2016 let sweep = if sweep < 1e-9 { tau } else { sweep };
2017 Some(ArcGeometry {
2018 centre,
2019 radius,
2020 base,
2021 sweep,
2022 turn,
2023 })
2024}
2025
2026fn collect_segments(
2029 collected: &mut Vec<ToolpathSegment>,
2030 kind: ExtrusionKind,
2031 start: [f64; 3],
2032 end: [f64; 3],
2033 arc: Option<ArcGeometry>,
2034) {
2035 #[expect(
2036 clippy::cast_possible_truncation,
2037 reason = "bed millimetres are far inside f32's range; a toolpath is drawn, not measured"
2038 )]
2039 let at = |x: f64, y: f64| [x as f32, y as f32];
2040 let Some(arc) = arc else {
2041 collected.push(ToolpathSegment {
2042 from_mm: at(start[0], start[1]),
2043 to_mm: at(end[0], end[1]),
2044 kind,
2045 });
2046 return;
2047 };
2048 let length = arc.sweep * arc.radius;
2049 let chords = (length / CHORD_MM).ceil().clamp(1.0, 4096.0);
2050 let (from, step) = match arc.turn {
2051 Turn::CounterClockwise => (arc.base, arc.sweep / chords),
2052 Turn::Clockwise => (arc.base + arc.sweep, -arc.sweep / chords),
2053 };
2054 let mut previous = at(start[0], start[1]);
2055 let mut k = 1.0;
2056 while k < chords {
2057 let angle = from + step * k;
2058 let next = at(
2059 arc.centre[0] + arc.radius * angle.cos(),
2060 arc.centre[1] + arc.radius * angle.sin(),
2061 );
2062 collected.push(ToolpathSegment {
2063 from_mm: previous,
2064 to_mm: next,
2065 kind,
2066 });
2067 previous = next;
2068 k += 1.0;
2069 }
2070 collected.push(ToolpathSegment {
2071 from_mm: previous,
2072 to_mm: at(end[0], end[1]),
2073 kind,
2074 });
2075}
2076
2077fn centre_of_radius(radius: f64, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<[f64; 2]> {
2082 let chord = [end[0] - start[0], end[1] - start[1]];
2083 let length = chord[0].hypot(chord[1]);
2084 if length <= TRAVEL_MM || length > 2.0 * radius.abs() {
2085 return None;
2086 }
2087 let rise = (radius * radius - length * length / 4.0).max(0.0).sqrt();
2088 let left = match turn {
2089 Turn::Clockwise => -1.0,
2090 Turn::CounterClockwise => 1.0,
2091 };
2092 let side = left * radius.signum() * rise / length;
2093 Some([
2094 start[0] + chord[0] / 2.0 - chord[1] * side,
2095 start[1] + chord[1] / 2.0 + chord[0] * side,
2096 ])
2097}
2098
2099fn words(command: &[u8]) -> Words {
2105 let mut found = Words {
2106 held: [Word {
2107 letter: 0,
2108 value: f64::NAN,
2109 }; WORD_COUNT],
2110 len: 0,
2111 first_code: None,
2112 second_code: None,
2113 numbered: false,
2114 };
2115 let length = command.len();
2116 let mut at = 0;
2117 while at < length {
2118 let letter = command[at];
2119 if letter == b';' || letter == b'*' {
2120 break;
2121 }
2122 at += 1;
2123 let upper = match letter {
2124 b'a'..=b'z' => letter - (b'a' - b'A'),
2125 b'A'..=b'Z' => letter,
2126 _ => continue,
2127 };
2128 let start = at;
2129 let (value, next) = number_at(command, at);
2130 at = next;
2131 let text = &command[start..at];
2132 if found.len == 0 {
2135 found.first_code = whole_number(text);
2136 found.numbered = upper == b'N';
2137 } else if found.len == 1 {
2138 found.second_code = whole_number(text);
2139 }
2140 if found.len < WORD_COUNT {
2141 found.held[found.len] = Word {
2142 letter: upper,
2143 value,
2144 };
2145 found.len += 1;
2146 }
2147 }
2148 found
2149}
2150
2151fn number_at(line: &[u8], mut at: usize) -> (f64, usize) {
2160 let start = at;
2161 while at < line.len()
2162 && !matches!(line[at], b' ' | b'\t' | b';' | b'*' | b'A'..=b'Z' | b'a'..=b'z')
2163 {
2164 at += 1;
2165 }
2166 (decimal(&line[start..at]).unwrap_or(f64::NAN), at)
2167}
2168
2169#[derive(Debug, Clone, Copy, Default)]
2173struct Move {
2174 x: Option<f64>,
2176 y: Option<f64>,
2178 z: Option<f64>,
2180 e: Option<f64>,
2182 i: Option<f64>,
2184 j: Option<f64>,
2186 r: Option<f64>,
2188}
2189
2190impl Move {
2191 fn of(words: &[Word]) -> Self {
2193 Self {
2194 x: number(words, 'X'),
2195 y: number(words, 'Y'),
2196 z: number(words, 'Z'),
2197 e: number(words, 'E'),
2198 i: number(words, 'I'),
2199 j: number(words, 'J'),
2200 r: number(words, 'R'),
2201 }
2202 }
2203}
2204
2205fn move_of(line: &[u8]) -> Move {
2210 let mut found = Move::default();
2211 let length = line.len();
2212 let mut at = 0;
2213 while at < length {
2214 let letter = line[at];
2215 at += 1;
2216 let slot = match letter {
2217 b';' | b'*' => break,
2218 b'X' | b'x' => &mut found.x,
2219 b'Y' | b'y' => &mut found.y,
2220 b'Z' | b'z' => &mut found.z,
2221 b'E' | b'e' => &mut found.e,
2222 b'I' | b'i' => &mut found.i,
2223 b'J' | b'j' => &mut found.j,
2224 b'R' | b'r' => &mut found.r,
2225 b'A'..=b'Z' | b'a'..=b'z' => {
2226 while at < length && !matches!(line[at], b' ' | b'\t' | b';' | b'*') {
2227 at += 1;
2228 }
2229 continue;
2230 }
2231 _ => continue,
2232 };
2233 let (value, next) = number_at(line, at);
2234 at = next;
2235 if slot.is_none() {
2236 *slot = Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
2237 }
2238 }
2239 found
2240}
2241
2242#[derive(Debug, Clone, Copy)]
2245struct Word {
2246 letter: u8,
2248 value: f64,
2250}
2251
2252struct Words {
2254 held: [Word; WORD_COUNT],
2256 len: usize,
2258 first_code: Option<u32>,
2260 second_code: Option<u32>,
2262 numbered: bool,
2264}
2265
2266impl Words {
2267 fn as_slice(&self) -> &[Word] {
2269 &self.held[..self.len]
2270 }
2271}
2272
2273fn whole_number(text: &[u8]) -> Option<u32> {
2275 let mut value: u32 = 0;
2276 let mut at = 0;
2277 while at < text.len() {
2278 let byte = text[at];
2279 if !byte.is_ascii_digit() {
2280 return None;
2281 }
2282 value = value.checked_mul(10)?.checked_add(u32::from(byte - b'0'))?;
2283 at += 1;
2284 }
2285 (!text.is_empty()).then_some(value)
2286}
2287
2288fn decimal(text: &[u8]) -> Option<f64> {
2290 core::str::from_utf8(text).ok()?.parse::<f64>().ok()
2291}
2292
2293fn number(words: &[Word], letter: char) -> Option<f64> {
2296 let mut at = 0;
2297 while at < words.len() {
2298 let Word {
2299 letter: word,
2300 value,
2301 } = words[at];
2302 if char::from(word) == letter {
2303 return Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
2304 }
2305 at += 1;
2306 }
2307 None
2308}
2309
2310#[must_use]
2313pub fn index_of(pieces: &[&[u8]]) -> GcodeIndex {
2314 let mut builder = IndexBuilder::new();
2315 for piece in pieces {
2316 let _ = builder.take(piece);
2317 }
2318 builder.finish()
2319}
2320
2321#[derive(Debug, Default)]
2323enum Slot {
2324 #[default]
2326 Empty,
2327 Building(Vec<Waker>),
2329 Ready(Arc<GcodeIndex>),
2331}
2332
2333#[derive(Debug, Default)]
2335pub struct GcodeIndexes {
2336 slots: Mutex<BTreeMap<PrintId, Slot>>,
2338 looked: Mutex<BTreeMap<PrintId, Vec<(Timestamp, i64)>>>,
2344}
2345
2346#[derive(Debug)]
2348pub enum Claimed<'a> {
2349 Ready(Arc<GcodeIndex>),
2351 Build(BuildClaim<'a>),
2353}
2354
2355#[derive(Debug)]
2358pub struct BuildClaim<'a> {
2359 indexes: &'a GcodeIndexes,
2361 print_id: PrintId,
2363 done: bool,
2365}
2366
2367impl BuildClaim<'_> {
2368 #[must_use]
2370 pub fn finish(mut self, index: GcodeIndex) -> Arc<GcodeIndex> {
2371 let index = Arc::new(index);
2372 self.settle(Slot::Ready(Arc::clone(&index)));
2373 self.done = true;
2374 index
2375 }
2376
2377 fn settle(&self, next: Slot) {
2379 let waiting = {
2380 let mut slots = self.indexes.held();
2381 let slot = slots.entry(self.print_id).or_default();
2382 match core::mem::replace(slot, next) {
2383 Slot::Building(waiting) => waiting,
2384 Slot::Empty | Slot::Ready(_) => Vec::new(),
2385 }
2386 };
2387 for waker in waiting {
2388 waker.wake();
2389 }
2390 }
2391}
2392
2393impl Drop for BuildClaim<'_> {
2394 fn drop(&mut self) {
2395 if !self.done {
2396 self.settle(Slot::Empty);
2397 }
2398 }
2399}
2400
2401impl GcodeIndexes {
2402 fn held(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, Slot>> {
2404 self.slots.lock().unwrap_or_else(PoisonError::into_inner)
2405 }
2406
2407 pub const fn claim(&self, print_id: PrintId) -> Claim<'_> {
2410 Claim {
2411 indexes: self,
2412 print_id,
2413 }
2414 }
2415
2416 #[must_use]
2418 pub fn built(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
2419 match self.held().get(&print_id) {
2420 Some(Slot::Ready(index)) => Some(Arc::clone(index)),
2421 _ => None,
2422 }
2423 }
2424}
2425
2426#[derive(Debug)]
2428pub struct Claim<'a> {
2429 indexes: &'a GcodeIndexes,
2431 print_id: PrintId,
2433}
2434
2435impl<'a> Future for Claim<'a> {
2436 type Output = Claimed<'a>;
2437
2438 fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
2439 let mut slots = self.indexes.held();
2440 let slot = slots.entry(self.print_id).or_default();
2441 match slot {
2442 Slot::Ready(index) => Poll::Ready(Claimed::Ready(Arc::clone(index))),
2443 Slot::Building(waiting) => {
2444 if !waiting.iter().any(|held| held.will_wake(context.waker())) {
2445 waiting.push(context.waker().clone());
2446 }
2447 Poll::Pending
2448 }
2449 Slot::Empty => {
2450 *slot = Slot::Building(Vec::new());
2451 Poll::Ready(Claimed::Build(BuildClaim {
2452 indexes: self.indexes,
2453 print_id: self.print_id,
2454 done: false,
2455 }))
2456 }
2457 }
2458 }
2459}
2460
2461const HELD_INDEXES: usize = 16;
2465
2466impl GcodeIndexes {
2467 pub(crate) fn note_look(
2473 &self,
2474 print_id: PrintId,
2475 captured: Timestamp,
2476 position: i64,
2477 now: Timestamp,
2478 ) {
2479 let mut looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
2480 let frames = looked.entry(print_id).or_default();
2481 frames.push((captured, position));
2482 frames.sort_by_key(|(captured, _)| *captured);
2483 if let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) {
2484 let aged = frames.partition_point(|(captured, _)| *captured <= until);
2485 frames.drain(..aged.saturating_sub(1));
2486 }
2487 while looked.len() > HELD_INDEXES {
2488 let Some(oldest) = looked.keys().next().copied() else {
2489 break;
2490 };
2491 let _ = looked.remove(&oldest);
2492 }
2493 }
2494
2495 fn newest_look_until(&self, print_id: PrintId, until: Timestamp) -> Option<(Timestamp, i64)> {
2498 let looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
2499 looked
2500 .get(&print_id)?
2501 .iter()
2502 .rev()
2503 .find(|(captured, _)| *captured <= until)
2504 .copied()
2505 }
2506
2507 fn trim(&self, keep: PrintId) {
2509 let mut slots = self.held();
2510 let ready: Vec<PrintId> = slots
2511 .iter()
2512 .filter(|(print_id, slot)| **print_id != keep && matches!(slot, Slot::Ready(_)))
2513 .map(|(print_id, _)| *print_id)
2514 .collect();
2515 let over = slots.len().saturating_sub(HELD_INDEXES);
2516 for print_id in ready.into_iter().take(over) {
2517 slots.remove(&print_id);
2518 }
2519 }
2520}
2521
2522impl crate::supervisor::Supervisor {
2523 pub(crate) async fn slicer_plan(
2535 &self,
2536 print: &crate::records::PrintRecord,
2537 job: Option<&printobserver_printer_api::JobSnapshot>,
2538 interventions: &[crate::records::Intervention],
2539 ) -> Result<Option<SlicerPlan>, crate::error::CoreError> {
2540 let Some((position, file)) = job
2541 .and_then(|job| job.file_position_bytes.zip(job.file_name.as_deref()))
2542 .filter(|(_, file)| {
2543 print.ended_at.is_none() && print.file_name.as_deref() == Some(*file)
2544 })
2545 else {
2546 return Ok(None);
2547 };
2548 let Some(index) = self.index_of(print.id, file).await else {
2549 return Ok(None);
2550 };
2551 let (flow, fan) = self
2552 .changes_since(print.id, &index, position, interventions)
2553 .await?;
2554 let mut plan = index.plan_with(position, flow, fan);
2555 plan.change_waiting = self
2556 .planned_change_waiting(print.id)
2557 .await?
2558 .map(|waiting| waiting.reached.change);
2559 plan.rise = self.rise_of(print.id, &index, position).await?;
2560 if plan.rise.is_none() {
2561 plan.unknown.push(PlanFact::Rise);
2562 plan.unknown.sort_unstable();
2563 }
2564 Ok(Some(plan))
2565 }
2566
2567 async fn rise_of(
2572 &self,
2573 print_id: PrintId,
2574 index: &GcodeIndex,
2575 position: i64,
2576 ) -> Result<Option<Rise>, crate::error::CoreError> {
2577 use printobserver_types::EventPayload as _;
2578
2579 use crate::kinds::PeriodicObservationPayload;
2580
2581 let now = self.clock().now();
2582 let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) else {
2583 return Ok(None);
2584 };
2585 let events = self
2586 .stores()
2587 .events
2588 .history(crate::store::HistoryQuery {
2589 print_id,
2590 kinds: printobserver_types::EventKind::new(PeriodicObservationPayload::KIND)
2591 .into_iter()
2592 .collect(),
2593 since: None,
2594 until: Some(until),
2595 limit: Some(1),
2596 })
2597 .await?;
2598 let observed = events.first().and_then(|event| {
2599 let observed = event.payload_as::<PeriodicObservationPayload>()?.ok()?;
2600 let earlier = observed.job?.file_position_bytes?;
2601 Some((
2602 observed.frame_captured_at.unwrap_or(event.received_at),
2603 earlier,
2604 ))
2605 });
2606 let looked = self.gcode_indexes().newest_look_until(print_id, until);
2607 let newest = match (observed, looked) {
2608 (Some(observed), Some(looked)) => Some(if looked.0 > observed.0 {
2609 looked
2610 } else {
2611 observed
2612 }),
2613 (observed, looked) => observed.or(looked),
2614 };
2615 Ok(newest.and_then(|(since, earlier)| {
2616 Some(Rise {
2617 since,
2618 mm: index.height_and_rise_since(earlier, position)?,
2619 })
2620 }))
2621 }
2622
2623 pub async fn print_gcode_index(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
2628 let print = self.stores().prints.print(print_id).await.ok()??;
2635 if print.ended_at.is_some() {
2636 return None;
2637 }
2638 self.index_of(print.id, print.file_name.as_deref()?).await
2639 }
2640
2641 pub(crate) fn drop_gcode_spool(&self, print_id: PrintId) {
2643 if let Some(directory) = self.config().gcode_spool_dir.as_deref() {
2644 let _ = std::fs::remove_file(crate::toolpath::spool_path(directory, print_id));
2645 }
2646 }
2647
2648 pub async fn sweep_gcode_spools(&self) -> Result<(), crate::error::CoreError> {
2655 let Some(directory) = self.config().gcode_spool_dir.clone() else {
2656 return Ok(());
2657 };
2658 let open: Vec<String> = self
2659 .stores()
2660 .prints
2661 .open_prints()
2662 .await?
2663 .iter()
2664 .map(|print| print.id.to_string())
2665 .collect();
2666 let Ok(entries) = std::fs::read_dir(&directory) else {
2674 return Ok(());
2675 };
2676 for entry in entries.flatten() {
2677 let name = entry.file_name();
2678 let Some(print) = name
2680 .to_str()
2681 .and_then(|name| name.strip_suffix(crate::toolpath::SPOOL_SUFFIX))
2682 .filter(|print| print.parse::<PrintId>().is_ok())
2683 else {
2684 continue;
2685 };
2686 if !open.iter().any(|id| id == print) {
2687 let _ = std::fs::remove_file(entry.path());
2688 }
2689 }
2690 Ok(())
2691 }
2692
2693 async fn index_of(&self, print_id: PrintId, file: &str) -> Option<Arc<GcodeIndex>> {
2695 let file_name = printobserver_types::FileName::new(file).ok()?;
2697 let claim = match self.gcode_indexes().claim(print_id).await {
2698 Claimed::Ready(index) => return Some(index),
2699 Claimed::Build(claim) => claim,
2700 };
2701 let mut builder = self
2704 .config()
2705 .gcode_spool_dir
2706 .as_deref()
2707 .and_then(|directory| {
2708 IndexBuilder::spooling(crate::toolpath::spool_path(directory, print_id)).ok()
2709 })
2710 .unwrap_or_default();
2711 self.read_gcode(file_name.clone(), &mut builder)
2712 .await
2713 .ok()?;
2714 let index = claim.finish(builder.finish());
2715 self.gcode_indexes().trim(print_id);
2716 if let Ok(body) = printobserver_types::EventBody::of(&crate::kinds::GcodeIndexedPayload {
2717 file_name,
2718 bytes: index.bytes(),
2719 layers: u64::try_from(index.layer_count()).unwrap_or(u64::MAX),
2720 }) {
2721 let _ = self.append_system_event(print_id, body).await;
2724 }
2725 Some(index)
2726 }
2727
2728 async fn changes_since(
2737 &self,
2738 print_id: PrintId,
2739 index: &GcodeIndex,
2740 position: i64,
2741 interventions: &[crate::records::Intervention],
2742 ) -> Result<(Option<f64>, Option<f64>), crate::error::CoreError> {
2743 use printobserver_types::EventPayload as _;
2744
2745 use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload};
2746 use crate::records::PrintAction;
2747
2748 let kinds = [ActionRequestedPayload::KIND, ActionExecutedPayload::KIND]
2749 .iter()
2750 .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
2751 .collect();
2752 let events = self
2753 .stores()
2754 .events
2755 .history(crate::store::HistoryQuery {
2756 print_id,
2757 kinds,
2758 since: None,
2759 until: None,
2760 limit: Some(crate::store::MAX_HISTORY_LIMIT),
2761 })
2762 .await?;
2763 let requested: BTreeMap<crate::records::ActionId, PrintAction> = events
2764 .iter()
2765 .filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
2766 .filter_map(Result::ok)
2767 .map(|payload| (payload.action_id, payload.action))
2768 .collect();
2769 let mut flow = None;
2770 let mut fan = None;
2771 for executed in events
2773 .iter()
2774 .filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
2775 .filter_map(Result::ok)
2776 {
2777 let standing = executed
2778 .intervention_id
2779 .is_none_or(|opened| interventions.iter().any(|active| active.id == opened));
2780 let made = executed
2783 .file_position_bytes
2784 .and_then(|made| u64::try_from(made).ok())
2785 .unwrap_or(0);
2786 let after = |set: Option<SetInFile>| set.is_none_or(|set| made >= set.at);
2787 match requested.get(&executed.action_id) {
2788 Some(PrintAction::SetFlowrateFactor { factor, .. }) if flow.is_none() => {
2789 flow = Some((standing && after(index.flow_at(position))).then_some(*factor));
2790 }
2791 Some(PrintAction::SetFanPercent { percent, .. }) if fan.is_none() => {
2792 fan = Some((standing && after(index.fan_at(position))).then_some(*percent));
2793 }
2794 _ => {}
2795 }
2796 }
2797 Ok((flow.flatten(), fan.flatten()))
2798 }
2799}
2800
2801#[cfg(test)]
2802mod tests {
2803 use super::{GcodeIndexes, HELD_INDEXES, OVER_AIR, RISE_WINDOW_S, SUPPORTS, WALLS};
2804 use crate::toolpath::ExtrusionKind;
2805
2806 #[test]
2810 fn the_plans_type_names_map_to_the_kinds_the_toolpath_draws() {
2811 for name in WALLS {
2812 assert_eq!(ExtrusionKind::of_type(name), ExtrusionKind::Wall, "{name}");
2813 }
2814 for name in SUPPORTS {
2815 assert_eq!(
2816 ExtrusionKind::of_type(name),
2817 ExtrusionKind::Support,
2818 "{name}"
2819 );
2820 }
2821 for name in OVER_AIR {
2822 assert!(
2823 matches!(
2824 ExtrusionKind::of_type(name),
2825 ExtrusionKind::Bridge | ExtrusionKind::Overhang
2826 ),
2827 "{name}"
2828 );
2829 }
2830 }
2831 use printobserver_types::{PrintId, Timestamp};
2832
2833 fn after(start: Timestamp, seconds: i64) -> Timestamp {
2835 start.plus_seconds(seconds).expect("an instant")
2836 }
2837
2838 fn held(indexes: &GcodeIndexes, print_id: PrintId) -> Vec<(Timestamp, i64)> {
2840 indexes
2841 .looked
2842 .lock()
2843 .expect("the looks are held")
2844 .get(&print_id)
2845 .cloned()
2846 .unwrap_or_default()
2847 }
2848
2849 #[test]
2852 fn the_newest_aged_look_is_kept_and_every_older_one_let_go() {
2853 let indexes = GcodeIndexes::default();
2854 let print = PrintId::new();
2855 let start = Timestamp::now();
2856 indexes.note_look(print, start, 10, start);
2857 indexes.note_look(print, after(start, 60), 20, after(start, 60));
2858 let now = after(start, 60 + RISE_WINDOW_S + 30);
2859 indexes.note_look(print, now, 30, now);
2860
2861 assert_eq!(
2862 held(&indexes, print),
2863 vec![(after(start, 60), 20), (now, 30)]
2864 );
2865 assert_eq!(
2866 indexes.newest_look_until(print, after(now, -RISE_WINDOW_S)),
2867 Some((after(start, 60), 20))
2868 );
2869 assert_eq!(indexes.newest_look_until(print, after(start, 30)), None);
2870 }
2871
2872 #[test]
2875 fn the_looks_of_prints_beyond_the_held_count_are_let_go_oldest_first() {
2876 let indexes = GcodeIndexes::default();
2877 let now = Timestamp::now();
2878 let mut prints: Vec<PrintId> = (0..=HELD_INDEXES).map(|_| PrintId::new()).collect();
2879 prints.sort_unstable();
2880 for print in &prints {
2881 indexes.note_look(*print, now, 1, now);
2882 }
2883
2884 assert!(held(&indexes, prints[0]).is_empty());
2885 for print in &prints[1..] {
2886 assert_eq!(held(&indexes, *print), vec![(now, 1)]);
2887 }
2888 }
2889}