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 #[must_use]
546 pub fn busiest_layer(&self) -> Option<(usize, i64)> {
547 self.layers
548 .iter()
549 .map(|layer| {
550 (
551 usize::try_from(layer.types.count_ones()).unwrap_or(usize::MAX),
552 i64::try_from(layer.at).unwrap_or(i64::MAX),
553 )
554 })
555 .reduce(|best, next| if next.0 > best.0 { next } else { best })
556 }
557
558 #[must_use]
560 pub fn flow_at(&self, position: i64) -> Option<SetInFile> {
561 last_at(&self.flow, position).map(|mark| SetInFile {
562 value: mark.value,
563 at: mark.at,
564 })
565 }
566
567 #[must_use]
570 pub fn fan_at(&self, position: i64) -> Option<SetInFile> {
571 last_at(&self.fan, position).map(|mark| SetInFile {
572 value: mark.value,
573 at: mark.at,
574 })
575 }
576
577 #[must_use]
580 pub fn plan_at(&self, position: i64) -> SlicerPlan {
581 self.plan_with(position, None, None)
582 }
583
584 #[must_use]
588 pub fn plan_with(
589 &self,
590 position: i64,
591 flow_changed: Option<f64>,
592 fan_changed: Option<f64>,
593 ) -> SlicerPlan {
594 let mut unknown = Vec::new();
595 let layer_index = self
596 .layers
597 .iter()
598 .rposition(|layer| reached(layer.at, position));
599 let final_z_mm = self.layers.last().and_then(|layer| layer.z_mm);
600 if self.layers.is_empty() {
601 unknown.push(PlanFact::Layer);
602 }
603 if final_z_mm.is_none() {
604 unknown.push(PlanFact::FinalZ);
605 }
606 if !self.labelled_types {
607 unknown.push(PlanFact::Types);
608 }
609 let types = layer_index.map_or_else(Vec::new, |index| {
610 let bits = self.layers[index].types;
611 self.type_names
612 .iter()
613 .enumerate()
614 .filter(|(bit, _)| bits & (1 << bit) != 0)
615 .map(|(_, name)| name.clone())
616 .collect()
617 });
618 let minutes_left = last_at(&self.time_left, position).map(|mark| mark.value);
619 if minutes_left.is_none() {
620 unknown.push(PlanFact::MinutesLeft);
621 }
622 let flow_factor = set_value(
623 self.flow_at(position).map(|set| set.value),
624 flow_changed,
625 PlanFact::FlowFactor,
626 &mut unknown,
627 );
628 let fan_percent = set_value(
629 self.fan_at(position).map(|set| set.value),
630 fan_changed,
631 PlanFact::FanPercent,
632 &mut unknown,
633 );
634 if !self.labelled_objects {
635 unknown.push(PlanFact::Objects);
636 }
637 unknown.sort_unstable();
638 let in_force =
639 |set: &Option<SetValue>| set.as_ref().and_then(|set| set.changed.or(set.file));
640 let mut at_odds = Vec::new();
641 if let Some(index) = layer_index {
642 let shown = self.layers[index.saturating_sub(LAYERS_SHOWN_BELOW)..=index]
643 .iter()
644 .fold(0, |bits, layer| bits | layer.types);
645 if in_force(&fan_percent).is_some_and(|fan| fan <= 0.0)
646 && shown & self.type_bits(&OVER_AIR) != 0
647 {
648 at_odds.push(PlanMismatch::FanOffOverBridges);
649 }
650 if in_force(&flow_factor).is_some_and(|flow| flow < FLOW_WELL_UNDER_ONE)
651 && self.layers[index].types & self.type_bits(&WALLS) != 0
652 {
653 at_odds.push(PlanMismatch::FlowLowOverWalls);
654 }
655 }
656 let next_change = self
657 .changes
658 .get(self.changes_read(position))
659 .map(|mark| mark.change.clone());
660 let minutes_to_next_change = next_change
661 .as_ref()
662 .and_then(|_| last_at(&self.change_minutes, position))
663 .map(|mark| mark.value);
664 SlicerPlan {
665 expected_color: self.expected_color_at(position),
666 next_change,
667 minutes_to_next_change,
668 change_waiting: None,
669 layer: layer_index.map(|index| index + 1),
670 z_mm: layer_index.and_then(|index| self.layers[index].z_mm),
671 final_z_mm,
672 types,
673 minutes_left,
674 flow_factor,
675 fan_percent,
676 object_count: self.labelled_objects.then_some(self.objects.len()),
677 objects: self.objects.clone(),
678 rise: None,
679 at_odds,
680 unknown,
681 }
682 }
683
684 fn type_bits(&self, names: &[&str]) -> u64 {
686 self.type_names
687 .iter()
688 .enumerate()
689 .filter(|(_, name)| names.contains(&name.as_str()))
690 .fold(0, |bits, (bit, _)| bits | (1 << bit))
691 }
692
693 #[must_use]
702 pub fn risen_since(&self, earlier: i64, now: i64) -> Option<f64> {
703 self.height_and_rise_since(earlier, now)
704 .map(|[_, risen]| risen)
705 }
706
707 #[must_use]
711 pub fn height_and_rise_since(&self, earlier: i64, now: i64) -> Option<[f64; 2]> {
712 let at = |position| {
713 self.layers
714 .iter()
715 .rposition(|layer| reached(layer.at, position))
716 .filter(|index| self.layers[*index].z_mm.is_some())
717 };
718 let (then, now) = (at(earlier)?, at(now)?);
719 let supports = self.type_bits(&SUPPORTS);
720 let lays_the_part = |layer: &&Layer| layer.types & !supports != 0;
721 let mut top = self.layers[..=then]
724 .iter()
725 .rev()
726 .filter(lays_the_part)
727 .find_map(|layer| layer.z_mm)
728 .or(self.layers[then].z_mm)?;
729 let height = top;
730 let mut risen = 0.0;
731 for layer in self
732 .layers
733 .iter()
734 .take(now + 1)
735 .skip(then + 1)
736 .filter(lays_the_part)
737 {
738 let Some(z) = layer.z_mm else { continue };
739 risen += (z - top).max(0.0);
740 top = top.max(z);
741 }
742 let tenth = |mm: f64| (mm * 10.0).round() / 10.0;
743 Some([tenth(height), tenth(risen)])
744 }
745}
746
747fn set_value(
750 file: Option<f64>,
751 changed: Option<f64>,
752 fact: PlanFact,
753 unknown: &mut Vec<PlanFact>,
754) -> Option<SetValue> {
755 if file.is_none() {
756 unknown.push(fact);
757 }
758 (file.is_some() || changed.is_some()).then_some(SetValue { file, changed })
759}
760
761const fn waits_at(change: &PlannedChange, position: u64) -> bool {
763 position >= change.offset_bytes && position - change.offset_bytes <= PLANNED_CHANGE_REACH_BYTES
764}
765
766fn millimetres(length: f64) -> f64 {
768 (length.max(0.0) * 1000.0).round() / 1000.0
769}
770
771fn reached(at: u64, position: i64) -> bool {
773 u64::try_from(position).is_ok_and(|position| at <= position)
774}
775
776fn last_at<T: Copy>(marks: &[Mark<T>], position: i64) -> Option<Mark<T>> {
778 let Ok(position) = u64::try_from(position) else {
779 return None;
780 };
781 let reached = marks.partition_point(|mark| mark.at <= position);
782 reached.checked_sub(1).map(|index| marks[index])
783}
784
785#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
788#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
789#[schemars(crate = "printobserver_types::schemars")]
790pub struct SetValue {
791 #[serde(default, skip_serializing_if = "Option::is_none")]
793 pub file: Option<f64>,
794 #[serde(default, skip_serializing_if = "Option::is_none")]
797 pub changed: Option<f64>,
798}
799
800pub type BedArea = [i64; 4];
805
806#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
809#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
810#[schemars(crate = "printobserver_types::schemars")]
811pub struct Rise {
812 pub since: Timestamp,
817 pub mm: [f64; 2],
823}
824
825pub(crate) fn null_is_sent(schema: &mut printobserver_types::schemars::Schema) {
833 use printobserver_types::serde_json::Value;
834 if let Some(Value::Object(properties)) = schema.get_mut("properties") {
835 for property in properties.values_mut() {
836 if property.get("properties").is_some()
837 && let Ok(inline) =
838 printobserver_types::schemars::Schema::try_from(core::mem::take(property))
839 {
840 let mut inline = inline;
841 null_is_sent(&mut inline);
842 *property = inline.to_value();
843 }
844 }
845 }
846 let nullable = |property: &Value| match property.get("type") {
847 Some(Value::Array(types)) => types.iter().any(|named| named == "null"),
848 _ => property
849 .get("anyOf")
850 .and_then(Value::as_array)
851 .is_some_and(|arms| {
852 arms.iter()
853 .any(|arm| arm.get("type") == Some(&Value::from("null")))
854 }),
855 };
856 let sent: Vec<Value> = schema
857 .get("properties")
858 .and_then(Value::as_object)
859 .map(|properties| {
860 properties
861 .iter()
862 .filter(|(_, property)| nullable(property))
863 .map(|(name, _)| Value::from(name.as_str()))
864 .collect()
865 })
866 .unwrap_or_default();
867 if sent.is_empty() {
868 return;
869 }
870 let required = schema
871 .ensure_object()
872 .entry("required")
873 .or_insert_with(|| Value::Array(Vec::new()));
874 if let Value::Array(required) = required {
875 for name in sent {
876 if !required.contains(&name) {
877 required.push(name);
878 }
879 }
880 }
881}
882
883#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
885#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
886#[schemars(crate = "printobserver_types::schemars")]
887pub enum PlannedChangeKind {
888 ColorChange,
890 Pause,
892}
893
894#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
897#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
898#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
899pub struct PlannedChange {
900 pub index: u32,
902 pub kind: PlannedChangeKind,
904 pub offset_bytes: u64,
906 pub layer: u32,
909 pub z_mm: f64,
911 pub color: Option<String>,
915}
916
917#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
919#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
920#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
921pub struct PlannedSegment {
922 pub segment: u32,
925 pub color: Option<String>,
928 pub filament_mm: f64,
930}
931
932#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
934#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
935#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
936pub struct PlannedChanges {
937 pub changes: Vec<PlannedChange>,
939 pub segments: Vec<PlannedSegment>,
941 pub waiting: Option<u32>,
944 pub expected_color: Option<String>,
947}
948
949impl Sample for PlannedChange {
950 fn sample_full() -> Self {
951 Self {
952 index: 0,
953 kind: PlannedChangeKind::ColorChange,
954 offset_bytes: 48_213,
955 layer: 12,
956 z_mm: 2.4,
957 color: Some("#FF0000".to_owned()),
958 }
959 }
960
961 fn sample_alternates() -> Vec<Self> {
962 vec![Self {
963 index: 1,
964 kind: PlannedChangeKind::Pause,
965 offset_bytes: 96_410,
966 layer: 24,
967 z_mm: 4.8,
968 color: None,
969 }]
970 }
971}
972
973impl Sample for PlannedSegment {
974 fn sample_full() -> Self {
975 Self {
976 segment: 1,
977 color: Some("#FF0000".to_owned()),
978 filament_mm: 812.4,
979 }
980 }
981
982 fn sample_alternates() -> Vec<Self> {
983 vec![Self {
984 segment: 0,
985 color: None,
986 filament_mm: 0.0,
987 }]
988 }
989}
990
991impl Sample for PlannedChanges {
992 fn sample_full() -> Self {
993 Self {
994 changes: vec![PlannedChange::sample_full()],
995 segments: vec![
996 PlannedSegment {
997 segment: 0,
998 color: Some("#FFFFFF".to_owned()),
999 filament_mm: 301.7,
1000 },
1001 PlannedSegment::sample_full(),
1002 ],
1003 waiting: Some(0),
1004 expected_color: Some("#FF0000".to_owned()),
1005 }
1006 }
1007
1008 fn sample_alternates() -> Vec<Self> {
1009 vec![Self {
1010 waiting: None,
1011 expected_color: None,
1012 ..Self::sample_full()
1013 }]
1014 }
1015}
1016
1017#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1020#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1021#[schemars(crate = "printobserver_types::schemars")]
1022pub enum PlanMismatch {
1023 FanOffOverBridges,
1026 FlowLowOverWalls,
1028}
1029
1030#[derive(
1032 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
1033)]
1034#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1035#[schemars(crate = "printobserver_types::schemars")]
1036pub enum PlanFact {
1037 Layer,
1039 FinalZ,
1041 Types,
1043 MinutesLeft,
1045 FlowFactor,
1047 FanPercent,
1049 Objects,
1051 Rise,
1055}
1056
1057#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1064#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1065#[schemars(crate = "printobserver_types::schemars")]
1066pub struct SlicerPlan {
1067 #[serde(default, skip_serializing_if = "Option::is_none")]
1071 pub expected_color: Option<String>,
1072 #[serde(default, skip_serializing_if = "Option::is_none")]
1075 pub next_change: Option<PlannedChange>,
1076 #[serde(default, skip_serializing_if = "Option::is_none")]
1080 pub minutes_to_next_change: Option<i64>,
1081 #[serde(default, skip_serializing_if = "Option::is_none")]
1084 pub change_waiting: Option<PlannedChange>,
1085 #[serde(default, skip_serializing_if = "Option::is_none")]
1088 pub layer: Option<usize>,
1089 #[serde(default, skip_serializing_if = "Option::is_none")]
1091 pub z_mm: Option<f64>,
1092 #[serde(default, skip_serializing_if = "Option::is_none")]
1094 pub final_z_mm: Option<f64>,
1095 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1098 pub types: Vec<String>,
1099 #[serde(default, skip_serializing_if = "Option::is_none")]
1101 pub minutes_left: Option<i64>,
1102 #[serde(default, skip_serializing_if = "Option::is_none")]
1104 pub flow_factor: Option<SetValue>,
1105 #[serde(default, skip_serializing_if = "Option::is_none")]
1107 pub fan_percent: Option<SetValue>,
1108 #[serde(default, skip_serializing_if = "Option::is_none")]
1110 pub object_count: Option<usize>,
1111 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1115 pub objects: Vec<BedArea>,
1116 #[serde(default, skip_serializing_if = "Option::is_none")]
1119 pub rise: Option<Rise>,
1120 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1122 pub at_odds: Vec<PlanMismatch>,
1123 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1126 pub unknown: Vec<PlanFact>,
1127}
1128
1129impl Sample for SlicerPlan {
1130 fn sample_full() -> Self {
1131 Self {
1132 expected_color: Some("#FF0000".to_owned()),
1133 next_change: Some(PlannedChange::sample_full()),
1134 minutes_to_next_change: Some(17),
1135 change_waiting: Some(PlannedChange::sample_full()),
1136 layer: Some(12),
1137 z_mm: Some(2.4),
1138 types: vec![
1139 "Perimeter".to_owned(),
1140 "External perimeter".to_owned(),
1141 "Support material".to_owned(),
1142 ],
1143 final_z_mm: Some(30.0),
1144 minutes_left: Some(42),
1145 flow_factor: Some(SetValue {
1146 file: Some(1.0),
1147 changed: Some(0.95),
1148 }),
1149 fan_percent: Some(SetValue {
1150 file: Some(100.0),
1151 changed: None,
1152 }),
1153 object_count: Some(1),
1154 objects: vec![[100, 99, 150, 117]],
1155 rise: Some(Rise {
1156 since: Timestamp::sample_full(),
1157 mm: [7.2, 4.8],
1158 }),
1159 at_odds: vec![PlanMismatch::FlowLowOverWalls],
1160 unknown: vec![PlanFact::Objects],
1161 }
1162 }
1163
1164 fn sample_minimal() -> Self {
1165 Self {
1166 expected_color: None,
1167 next_change: None,
1168 minutes_to_next_change: None,
1169 change_waiting: None,
1170 layer: None,
1171 z_mm: None,
1172 final_z_mm: None,
1173 types: Vec::new(),
1174 minutes_left: None,
1175 flow_factor: None,
1176 fan_percent: None,
1177 object_count: None,
1178 objects: Vec::new(),
1179 rise: None,
1180 at_odds: Vec::new(),
1181 unknown: Vec::new(),
1182 }
1183 }
1184}
1185
1186#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1188enum Positioning {
1189 #[default]
1191 Absolute,
1192 Relative,
1194}
1195
1196#[derive(Debug, Default)]
1199pub struct IndexBuilder {
1200 line: Vec<u8>,
1202 overlong: bool,
1204 read: u64,
1206 lines: u64,
1208 layers: Vec<Layer>,
1210 type_names: Vec<String>,
1212 labelled_types: bool,
1214 current_type: Option<usize>,
1216 time_left: Vec<Mark<i64>>,
1218 flow: Vec<Mark<f64>>,
1220 fan: Vec<Mark<f64>>,
1222 objects: Vec<ObjectDraft>,
1224 object_numbers: BTreeMap<i64, usize>,
1226 current_object: Option<usize>,
1229 labelled_objects: bool,
1231 at: [f64; 3],
1233 e: f64,
1235 axes: Positioning,
1237 extruder: Positioning,
1239 line_began: u64,
1241 all: Reach,
1243 blocks: Vec<(u64, usize)>,
1246 spool: Option<Spooling>,
1248 collected: Option<Vec<ToolpathSegment>>,
1250 reached_last: Option<[f64; 2]>,
1252 changes: Vec<ChangeDraft>,
1254 change_minutes: Vec<Mark<i64>>,
1256 colour_comment: Option<(u64, String)>,
1258 first_colour: Option<String>,
1260 extruded_mm: f64,
1262 laid_in_layers: usize,
1265}
1266
1267#[derive(Debug, Clone, PartialEq)]
1270struct ChangeDraft {
1271 kind: PlannedChangeKind,
1273 offset: u64,
1275 at: u64,
1277 layer: usize,
1280 color: Option<String>,
1282 fed_before_mm: f64,
1284}
1285
1286#[derive(Debug)]
1288struct Spooling {
1289 path: std::path::PathBuf,
1291 writer: std::io::BufWriter<std::fs::File>,
1293 failed: bool,
1295}
1296
1297impl GcodeSink for IndexBuilder {
1298 fn take(&mut self, piece: &[u8]) -> ControlFlow<()> {
1299 if let Some(spool) = self.spool.as_mut().filter(|spool| !spool.failed) {
1309 use std::io::Write as _;
1310 spool.failed = spool.writer.write_all(piece).is_err();
1311 }
1312 let mut start = 0;
1313 let mut at = 0;
1314 while at < piece.len() {
1315 if piece[at] == b'\n' {
1316 let head = &piece[start..at];
1317 self.read += u64::try_from(at + 1 - start).unwrap_or(u64::MAX);
1318 if self.line.is_empty() && !self.overlong {
1319 self.lines += 1;
1321 if head.len() <= LINE_LIMIT {
1322 self.read_line(head);
1323 }
1324 } else {
1325 self.hold(head);
1326 self.end_line();
1327 }
1328 self.line_began = self.read;
1329 start = at + 1;
1330 }
1331 at += 1;
1332 }
1333 let rest = &piece[start..];
1334 self.hold(rest);
1335 self.read += u64::try_from(rest.len()).unwrap_or(u64::MAX);
1336 ControlFlow::Continue(())
1337 }
1338}
1339
1340impl IndexBuilder {
1341 #[must_use]
1343 pub fn new() -> Self {
1344 Self::default()
1345 }
1346
1347 pub fn spooling(path: std::path::PathBuf) -> std::io::Result<Self> {
1355 let file = std::fs::File::create(&path)?;
1356 Ok(Self {
1357 spool: Some(Spooling {
1358 path,
1359 writer: std::io::BufWriter::with_capacity(1 << 16, file),
1360 failed: false,
1361 }),
1362 ..Self::default()
1363 })
1364 }
1365
1366 fn reading_layer(type_names: Vec<String>, head: Head) -> Self {
1369 Self {
1370 type_names,
1371 labelled_types: true,
1372 current_type: head.current_type,
1373 at: head.at,
1374 e: head.e,
1375 axes: head.axes,
1376 extruder: head.extruder,
1377 collected: Some(Vec::new()),
1378 ..Self::default()
1379 }
1380 }
1381
1382 #[must_use]
1385 pub fn finish(mut self) -> GcodeIndex {
1386 if !self.line.is_empty() || self.overlong {
1387 self.end_line();
1388 }
1389 let mut drafts: Vec<Option<ObjectDraft>> = self.objects.into_iter().map(Some).collect();
1390 let mut objects = Vec::new();
1391 let mut outlines = Vec::new();
1392 let mut outline_of = vec![None; drafts.len()];
1393 for place in self.object_numbers.into_values() {
1394 let Some(draft) = drafts.get_mut(place).and_then(Option::take) else {
1395 continue;
1396 };
1397 let Some([least_x, least_y, most_x, most_y]) = draft.bounds else {
1398 continue;
1399 };
1400 objects.push([
1401 whole(tenth(least_x).floor()),
1402 whole(tenth(least_y).floor()),
1403 whole(tenth(most_x).ceil()),
1404 whole(tenth(most_y).ceil()),
1405 ]);
1406 outline_of[place] = Some(outlines.len());
1407 outlines.push(draft.reach.outline().unwrap_or(ObjectOutline {
1408 hull_mm: Vec::new(),
1409 }));
1410 }
1411 if !self.labelled_objects {
1412 outlines.extend(self.all.outline());
1413 }
1414 let blocks = self
1415 .blocks
1416 .into_iter()
1417 .map(|(start, place)| (start, outline_of.get(place).copied().flatten()))
1418 .collect();
1419 let spool = self.spool.and_then(|mut spool| {
1420 use std::io::Write as _;
1421 if spool.failed || spool.writer.flush().is_err() {
1422 drop(spool.writer);
1423 let _ = std::fs::remove_file(&spool.path);
1424 return None;
1425 }
1426 Some(spool.path)
1427 });
1428 let changes = (0_u32..)
1429 .zip(self.changes)
1430 .map(|(index, draft)| {
1431 let layer = draft.layer.min(self.layers.len().saturating_sub(1));
1434 ChangeMark {
1435 change: PlannedChange {
1436 index,
1437 kind: draft.kind,
1438 offset_bytes: draft.offset,
1439 layer: u32::try_from(layer + 1).unwrap_or(u32::MAX),
1440 z_mm: self
1441 .layers
1442 .get(layer)
1443 .and_then(|held| held.z_mm)
1444 .unwrap_or(0.0),
1445 color: draft.color,
1446 },
1447 at: draft.at,
1448 fed_before_mm: draft.fed_before_mm,
1449 }
1450 })
1451 .collect();
1452 GcodeIndex {
1453 bytes: self.read,
1454 lines: self.lines,
1455 changes,
1456 change_minutes: self.change_minutes,
1457 first_colour: self.first_colour,
1458 extruded_mm: self.extruded_mm,
1459 layers: self.layers,
1460 type_names: self.type_names,
1461 labelled_types: self.labelled_types,
1462 time_left: self.time_left,
1463 flow: self.flow,
1464 fan: self.fan,
1465 objects,
1466 labelled_objects: self.labelled_objects,
1467 outlines,
1468 blocks,
1469 spool,
1470 }
1471 }
1472
1473 fn hold(&mut self, bytes: &[u8]) {
1475 if self.overlong {
1476 return;
1477 }
1478 if self.line.len() + bytes.len() > LINE_LIMIT {
1479 self.overlong = true;
1480 self.line.clear();
1481 return;
1482 }
1483 self.line.extend_from_slice(bytes);
1484 }
1485
1486 fn end_line(&mut self) {
1488 self.lines += 1;
1489 let line = core::mem::take(&mut self.line);
1490 if !self.overlong {
1491 self.read_line(&line);
1492 }
1493 self.overlong = false;
1494 self.line = line;
1495 self.line.clear();
1496 }
1497
1498 fn read_line(&mut self, raw: &[u8]) {
1500 let raw = raw.trim_ascii();
1501 if let Some(comment) = raw.strip_prefix(b";") {
1502 if let Ok(comment) = core::str::from_utf8(comment) {
1503 self.comment(comment.trim_end());
1504 }
1505 return;
1506 }
1507 if let [b'G', code @ b'0'..=b'3', b' ', rest @ ..] = raw {
1510 self.motion(u32::from(code - b'0'), &move_of(rest));
1511 return;
1512 }
1513 let held = words(raw);
1514 let mut words = held.as_slice();
1515 if let Some((Word { letter: b'N', .. }, rest)) = words.split_first() {
1517 words = rest;
1518 }
1519 let Some(first) = words.first() else {
1520 return;
1521 };
1522 let code = if held.numbered {
1523 held.second_code
1524 } else {
1525 held.first_code
1526 };
1527 match (char::from(first.letter), code) {
1528 ('G', Some(code @ 0..=3)) => self.motion(code, &Move::of(&words[1..])),
1529 ('G', Some(28)) => self.home(&words[1..]),
1530 ('G', Some(90)) => self.axes = Positioning::Absolute,
1531 ('G', Some(91)) => self.axes = Positioning::Relative,
1532 ('G', Some(92)) => self.declare(&words[1..]),
1533 ('M', Some(82)) => self.extruder = Positioning::Absolute,
1534 ('M', Some(83)) => self.extruder = Positioning::Relative,
1535 ('M', Some(73)) => self.estimate(&words[1..]),
1536 ('M', Some(221)) => self.flow_factor(&words[1..]),
1537 ('M', Some(106)) => self.fan_speed(&words[1..], Fan::Set),
1538 ('M', Some(107)) => self.fan_speed(&words[1..], Fan::Off),
1539 ('M', Some(486)) => self.object(raw, &words[1..]),
1540 ('M', Some(600)) => self.planned(PlannedChangeKind::ColorChange),
1541 ('M', Some(601)) => self.planned(PlannedChangeKind::Pause),
1542 _ => {}
1543 }
1544 }
1545
1546 fn comment(&mut self, comment: &str) {
1548 if comment == "LAYER_CHANGE" {
1549 self.layers.push(Layer {
1550 begins: self.line_began,
1551 head: Head {
1552 at: self.at,
1553 e: self.e,
1554 axes: self.axes,
1555 extruder: self.extruder,
1556 current_type: self.current_type,
1557 },
1558 at: self.read,
1559 z_mm: None,
1560 types: 0,
1561 });
1562 } else if let Some(z) = comment.strip_prefix("Z:") {
1563 if let Some(layer) = self.layers.last_mut()
1564 && layer.z_mm.is_none()
1565 {
1566 layer.z_mm = z
1569 .trim()
1570 .parse::<f64>()
1571 .ok()
1572 .filter(|z| (0.0..=AXIS_LIMIT).contains(z));
1573 }
1574 } else if let Some(change) = comment.strip_prefix("COLOR_CHANGE,") {
1575 self.colour_comment = change
1577 .split(',')
1578 .nth(1)
1579 .and_then(colour_of)
1580 .map(|colour| (self.lines, colour));
1581 } else if let Some(colours) = comment.trim_start().strip_prefix("filament_colour = ") {
1582 if self.first_colour.is_none() {
1583 self.first_colour = colours.split(';').next().and_then(colour_of);
1584 }
1585 } else if let Some(name) = comment.strip_prefix("TYPE:") {
1586 let name = name.trim();
1587 self.labelled_types = true;
1588 self.current_type = if name == NOT_THE_PART {
1589 None
1590 } else {
1591 self.intern(name)
1592 };
1593 }
1594 }
1595
1596 fn intern(&mut self, name: &str) -> Option<usize> {
1598 if let Some(bit) = self.type_names.iter().position(|held| held == name) {
1599 return Some(bit);
1600 }
1601 if self.type_names.len() >= TYPE_LIMIT {
1602 return None;
1603 }
1604 self.type_names.push(name.to_owned());
1605 Some(self.type_names.len() - 1)
1606 }
1607
1608 fn motion(&mut self, code: u32, words: &Move) {
1610 let start = self.at;
1613 let relative = self.axes == Positioning::Relative;
1614 if let Some(x) = words.x {
1615 self.place(0, x, relative);
1616 }
1617 if let Some(y) = words.y {
1618 self.place(1, y, relative);
1619 }
1620 if let Some(z) = words.z {
1621 self.place(2, z, relative);
1622 }
1623 let mut fed = 0.0;
1624 if let Some(value) = words.e {
1625 if relative || self.extruder == Positioning::Relative {
1626 self.e += value;
1627 fed = value;
1628 } else {
1629 fed = value - self.e;
1630 self.e = value;
1631 }
1632 }
1633 let travel = (self.at[0] - start[0]).hypot(self.at[1] - start[1]);
1634 self.extruded_mm += fed;
1635 if fed <= 0.0 || (travel <= TRAVEL_MM && code < 2) {
1636 return;
1637 }
1638 self.laid_in_layers = self.layers.len();
1639 if let (Some(layer), Some(bit)) = (self.layers.last_mut(), self.current_type) {
1640 layer.types |= 1 << bit;
1641 }
1642 let end = self.at;
1643 let turn = match code {
1644 2 => Some(Turn::Clockwise),
1645 3 => Some(Turn::CounterClockwise),
1646 _ => None,
1647 };
1648 let arc = turn.and_then(|turn| arc_of(words, turn, start, end));
1649 if let Some(collected) = self.collected.as_mut() {
1650 let kind = self
1651 .current_type
1652 .and_then(|bit| self.type_names.get(bit))
1653 .map_or(ExtrusionKind::Other, |name| ExtrusionKind::of_type(name));
1654 collect_segments(collected, kind, start, end, arc);
1655 return;
1656 }
1657 let part_of_plan = !(self.labelled_types && self.current_type.is_none());
1658 let reach = if let Some(object) = self.current_object {
1659 let draft = &mut self.objects[object];
1660 grow(&mut draft.bounds, start[0], start[1]);
1661 grow(&mut draft.bounds, end[0], end[1]);
1662 if let Some(turn) = turn {
1663 for [x, y] in arc_extremes(words, turn, start, end) {
1664 grow(&mut draft.bounds, x, y);
1665 }
1666 }
1667 &mut draft.reach
1668 } else if !self.labelled_objects && part_of_plan {
1669 &mut self.all
1670 } else {
1671 return;
1672 };
1673 if self.reached_last != Some([start[0], start[1]]) {
1676 reach.point(start[0], start[1]);
1677 }
1678 reach.point(end[0], end[1]);
1679 self.reached_last = Some([end[0], end[1]]);
1680 if let Some(arc) = arc {
1681 reach.arc(arc.centre, arc.radius, arc.base, arc.sweep);
1682 }
1683 }
1684
1685 fn place(&mut self, axis: usize, value: f64, relative: bool) {
1689 let landed = if relative {
1690 self.at[axis] + value
1691 } else {
1692 value
1693 };
1694 if landed.abs() <= AXIS_LIMIT {
1695 self.at[axis] = landed;
1696 }
1697 }
1698
1699 fn home(&mut self, words: &[Word]) {
1701 let named: Vec<usize> = ['X', 'Y', 'Z']
1702 .into_iter()
1703 .enumerate()
1704 .filter(|(_, letter)| words.iter().any(|word| char::from(word.letter) == *letter))
1705 .map(|(axis, _)| axis)
1706 .collect();
1707 if named.is_empty() {
1708 self.at = [0.0; 3];
1709 } else {
1710 for axis in named {
1711 self.at[axis] = 0.0;
1712 }
1713 }
1714 }
1715
1716 fn declare(&mut self, words: &[Word]) {
1719 if words.is_empty() {
1720 self.at = [0.0; 3];
1721 self.e = 0.0;
1722 return;
1723 }
1724 for (axis, letter) in ['X', 'Y', 'Z'].into_iter().enumerate() {
1725 if let Some(value) = number(words, letter).filter(|value| value.abs() <= AXIS_LIMIT) {
1726 self.at[axis] = value;
1727 }
1728 }
1729 if let Some(value) = number(words, 'E') {
1730 self.e = value;
1731 }
1732 }
1733
1734 fn estimate(&mut self, words: &[Word]) {
1737 if let Some(minutes) = number(words, 'C').filter(|minutes| *minutes >= 0.0) {
1738 self.change_minutes.push(Mark {
1739 at: self.read,
1740 value: whole(minutes),
1741 });
1742 }
1743 if number(words, 'P').is_none() {
1744 return;
1745 }
1746 if let Some(minutes) = number(words, 'R').filter(|minutes| *minutes >= 0.0) {
1747 self.time_left.push(Mark {
1748 at: self.read,
1749 value: whole(minutes),
1750 });
1751 }
1752 }
1753
1754 fn planned(&mut self, kind: PlannedChangeKind) {
1757 let named = self.colour_comment.take();
1758 if self.changes.len() >= CHANGE_LIMIT {
1759 return;
1760 }
1761 let color = match kind {
1762 PlannedChangeKind::ColorChange => named
1763 .filter(|(line, _)| line + 1 == self.lines)
1764 .map(|(_, colour)| colour),
1765 PlannedChangeKind::Pause => None,
1766 };
1767 let layer = if self.laid_in_layers == self.layers.len() {
1768 self.layers.len()
1769 } else {
1770 self.layers.len() - 1
1771 };
1772 self.changes.push(ChangeDraft {
1773 kind,
1774 offset: self.line_began,
1775 at: self.read,
1776 layer,
1777 color,
1778 fed_before_mm: self.extruded_mm,
1779 });
1780 }
1781
1782 fn flow_factor(&mut self, words: &[Word]) {
1784 if let Some(percent) = number(words, 'S').filter(|percent| *percent >= 0.0) {
1785 mark_setting(&mut self.flow, self.read, percent / 100.0);
1786 }
1787 }
1788
1789 fn fan_speed(&mut self, words: &[Word], command: Fan) {
1791 if number(words, 'P').is_some_and(|fan| fan != 0.0) {
1792 return;
1793 }
1794 let speed = match command {
1795 Fan::Off => 0.0,
1796 Fan::Set => number(words, 'S').unwrap_or(FAN_FULL),
1797 };
1798 let percent = (speed.clamp(0.0, FAN_FULL) / FAN_FULL * 100.0).round();
1799 mark_setting(&mut self.fan, self.read, percent);
1800 }
1801
1802 fn object(&mut self, raw: &[u8], words: &[Word]) {
1804 if raw
1807 .strip_prefix(b"M486")
1808 .is_some_and(|rest| rest.trim_ascii_start().starts_with(b"A"))
1809 {
1810 self.labelled_objects = true;
1811 return;
1812 }
1813 let Some(number) = number(words, 'S')
1816 .filter(|number| (number - number.round()).abs() < f64::EPSILON && *number >= -1.0)
1817 else {
1818 return;
1819 };
1820 self.labelled_objects = true;
1821 if number < 0.0 {
1822 self.current_object = None;
1823 self.reached_last = None;
1824 return;
1825 }
1826 let id = whole(number);
1827 let place = if let Some(place) = self.object_numbers.get(&id) {
1828 *place
1829 } else if self.objects.len() >= OBJECT_LIMIT {
1830 self.current_object = None;
1831 self.reached_last = None;
1832 return;
1833 } else {
1834 self.objects.push(ObjectDraft::default());
1835 self.object_numbers.insert(id, self.objects.len() - 1);
1836 self.objects.len() - 1
1837 };
1838 self.current_object = Some(place);
1839 self.reached_last = None;
1840 self.blocks.push((self.read, place));
1841 }
1842}
1843
1844fn colour_of(text: &str) -> Option<String> {
1846 let text = text.trim();
1847 let hex = text.strip_prefix('#')?;
1848 (hex.len() == 6 && hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
1849 .then(|| text.to_ascii_uppercase())
1850}
1851
1852fn mark_setting(marks: &mut Vec<Mark<f64>>, at: u64, value: f64) {
1856 marks.push(Mark { at, value });
1857}
1858
1859fn whole(value: f64) -> i64 {
1862 format!("{:.0}", value.round()).parse().unwrap_or_default()
1863}
1864
1865fn tenth(value: f64) -> f64 {
1869 (value * 10.0).round() / 10.0
1870}
1871
1872fn grow(bounds: &mut Option<[f64; 4]>, x: f64, y: f64) {
1874 *bounds = Some(match *bounds {
1875 None => [x, y, x, y],
1876 Some([least_x, least_y, most_x, most_y]) => {
1877 [least_x.min(x), least_y.min(y), most_x.max(x), most_y.max(y)]
1878 }
1879 });
1880}
1881
1882#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1884enum Turn {
1885 Clockwise,
1887 CounterClockwise,
1889}
1890
1891#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1894enum Fan {
1895 Set,
1897 Off,
1899}
1900
1901fn arc_extremes(
1910 words: &Move,
1911 turn: Turn,
1912 start: [f64; 3],
1913 end: [f64; 3],
1914) -> impl Iterator<Item = [f64; 2]> {
1915 let reach = arc_of(words, turn, start, end).map(|arc| {
1916 let ArcGeometry {
1917 centre,
1918 radius,
1919 base,
1920 sweep,
1921 ..
1922 } = arc;
1923 let tau = core::f64::consts::TAU;
1924 (0..4).filter_map(move |quarter| {
1925 let angle = core::f64::consts::FRAC_PI_2 * f64::from(quarter);
1926 ((angle - base).rem_euclid(tau) <= sweep + 1e-9).then(|| {
1927 [
1928 centre[0] + radius * angle.cos(),
1929 centre[1] + radius * angle.sin(),
1930 ]
1931 })
1932 })
1933 });
1934 reach.into_iter().flatten()
1935}
1936
1937#[derive(Debug, Clone, Copy)]
1939struct ArcGeometry {
1940 centre: [f64; 2],
1942 radius: f64,
1944 base: f64,
1947 sweep: f64,
1950 turn: Turn,
1952}
1953
1954fn arc_of(words: &Move, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<ArcGeometry> {
1958 let centre = words.r.map_or_else(
1959 || {
1960 Some([
1961 start[0] + words.i.unwrap_or(0.0),
1962 start[1] + words.j.unwrap_or(0.0),
1963 ])
1964 },
1965 |radius| centre_of_radius(radius, turn, start, end),
1966 )?;
1967 let radius = (start[0] - centre[0]).hypot(start[1] - centre[1]);
1968 let from = (start[1] - centre[1]).atan2(start[0] - centre[0]);
1969 let to = (end[1] - centre[1]).atan2(end[0] - centre[0]);
1970 let tau = core::f64::consts::TAU;
1971 let (base, sweep) = match turn {
1974 Turn::Clockwise => (to, (from - to).rem_euclid(tau)),
1975 Turn::CounterClockwise => (from, (to - from).rem_euclid(tau)),
1976 };
1977 let sweep = if sweep < 1e-9 { tau } else { sweep };
1978 Some(ArcGeometry {
1979 centre,
1980 radius,
1981 base,
1982 sweep,
1983 turn,
1984 })
1985}
1986
1987fn collect_segments(
1990 collected: &mut Vec<ToolpathSegment>,
1991 kind: ExtrusionKind,
1992 start: [f64; 3],
1993 end: [f64; 3],
1994 arc: Option<ArcGeometry>,
1995) {
1996 #[expect(
1997 clippy::cast_possible_truncation,
1998 reason = "bed millimetres are far inside f32's range; a toolpath is drawn, not measured"
1999 )]
2000 let at = |x: f64, y: f64| [x as f32, y as f32];
2001 let Some(arc) = arc else {
2002 collected.push(ToolpathSegment {
2003 from_mm: at(start[0], start[1]),
2004 to_mm: at(end[0], end[1]),
2005 kind,
2006 });
2007 return;
2008 };
2009 let length = arc.sweep * arc.radius;
2010 let chords = (length / CHORD_MM).ceil().clamp(1.0, 4096.0);
2011 let (from, step) = match arc.turn {
2012 Turn::CounterClockwise => (arc.base, arc.sweep / chords),
2013 Turn::Clockwise => (arc.base + arc.sweep, -arc.sweep / chords),
2014 };
2015 let mut previous = at(start[0], start[1]);
2016 let mut k = 1.0;
2017 while k < chords {
2018 let angle = from + step * k;
2019 let next = at(
2020 arc.centre[0] + arc.radius * angle.cos(),
2021 arc.centre[1] + arc.radius * angle.sin(),
2022 );
2023 collected.push(ToolpathSegment {
2024 from_mm: previous,
2025 to_mm: next,
2026 kind,
2027 });
2028 previous = next;
2029 k += 1.0;
2030 }
2031 collected.push(ToolpathSegment {
2032 from_mm: previous,
2033 to_mm: at(end[0], end[1]),
2034 kind,
2035 });
2036}
2037
2038fn centre_of_radius(radius: f64, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<[f64; 2]> {
2043 let chord = [end[0] - start[0], end[1] - start[1]];
2044 let length = chord[0].hypot(chord[1]);
2045 if length <= TRAVEL_MM || length > 2.0 * radius.abs() {
2046 return None;
2047 }
2048 let rise = (radius * radius - length * length / 4.0).max(0.0).sqrt();
2049 let left = match turn {
2050 Turn::Clockwise => -1.0,
2051 Turn::CounterClockwise => 1.0,
2052 };
2053 let side = left * radius.signum() * rise / length;
2054 Some([
2055 start[0] + chord[0] / 2.0 - chord[1] * side,
2056 start[1] + chord[1] / 2.0 + chord[0] * side,
2057 ])
2058}
2059
2060fn words(command: &[u8]) -> Words {
2066 let mut found = Words {
2067 held: [Word {
2068 letter: 0,
2069 value: f64::NAN,
2070 }; WORD_COUNT],
2071 len: 0,
2072 first_code: None,
2073 second_code: None,
2074 numbered: false,
2075 };
2076 let length = command.len();
2077 let mut at = 0;
2078 while at < length {
2079 let letter = command[at];
2080 if letter == b';' || letter == b'*' {
2081 break;
2082 }
2083 at += 1;
2084 let upper = match letter {
2085 b'a'..=b'z' => letter - (b'a' - b'A'),
2086 b'A'..=b'Z' => letter,
2087 _ => continue,
2088 };
2089 let start = at;
2090 let (value, next) = number_at(command, at);
2091 at = next;
2092 let text = &command[start..at];
2093 if found.len == 0 {
2096 found.first_code = whole_number(text);
2097 found.numbered = upper == b'N';
2098 } else if found.len == 1 {
2099 found.second_code = whole_number(text);
2100 }
2101 if found.len < WORD_COUNT {
2102 found.held[found.len] = Word {
2103 letter: upper,
2104 value,
2105 };
2106 found.len += 1;
2107 }
2108 }
2109 found
2110}
2111
2112fn number_at(line: &[u8], mut at: usize) -> (f64, usize) {
2121 let start = at;
2122 while at < line.len()
2123 && !matches!(line[at], b' ' | b'\t' | b';' | b'*' | b'A'..=b'Z' | b'a'..=b'z')
2124 {
2125 at += 1;
2126 }
2127 (decimal(&line[start..at]).unwrap_or(f64::NAN), at)
2128}
2129
2130#[derive(Debug, Clone, Copy, Default)]
2134struct Move {
2135 x: Option<f64>,
2137 y: Option<f64>,
2139 z: Option<f64>,
2141 e: Option<f64>,
2143 i: Option<f64>,
2145 j: Option<f64>,
2147 r: Option<f64>,
2149}
2150
2151impl Move {
2152 fn of(words: &[Word]) -> Self {
2154 Self {
2155 x: number(words, 'X'),
2156 y: number(words, 'Y'),
2157 z: number(words, 'Z'),
2158 e: number(words, 'E'),
2159 i: number(words, 'I'),
2160 j: number(words, 'J'),
2161 r: number(words, 'R'),
2162 }
2163 }
2164}
2165
2166fn move_of(line: &[u8]) -> Move {
2171 let mut found = Move::default();
2172 let length = line.len();
2173 let mut at = 0;
2174 while at < length {
2175 let letter = line[at];
2176 at += 1;
2177 let slot = match letter {
2178 b';' | b'*' => break,
2179 b'X' | b'x' => &mut found.x,
2180 b'Y' | b'y' => &mut found.y,
2181 b'Z' | b'z' => &mut found.z,
2182 b'E' | b'e' => &mut found.e,
2183 b'I' | b'i' => &mut found.i,
2184 b'J' | b'j' => &mut found.j,
2185 b'R' | b'r' => &mut found.r,
2186 b'A'..=b'Z' | b'a'..=b'z' => {
2187 while at < length && !matches!(line[at], b' ' | b'\t' | b';' | b'*') {
2188 at += 1;
2189 }
2190 continue;
2191 }
2192 _ => continue,
2193 };
2194 let (value, next) = number_at(line, at);
2195 at = next;
2196 if slot.is_none() {
2197 *slot = Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
2198 }
2199 }
2200 found
2201}
2202
2203#[derive(Debug, Clone, Copy)]
2206struct Word {
2207 letter: u8,
2209 value: f64,
2211}
2212
2213struct Words {
2215 held: [Word; WORD_COUNT],
2217 len: usize,
2219 first_code: Option<u32>,
2221 second_code: Option<u32>,
2223 numbered: bool,
2225}
2226
2227impl Words {
2228 fn as_slice(&self) -> &[Word] {
2230 &self.held[..self.len]
2231 }
2232}
2233
2234fn whole_number(text: &[u8]) -> Option<u32> {
2236 let mut value: u32 = 0;
2237 let mut at = 0;
2238 while at < text.len() {
2239 let byte = text[at];
2240 if !byte.is_ascii_digit() {
2241 return None;
2242 }
2243 value = value.checked_mul(10)?.checked_add(u32::from(byte - b'0'))?;
2244 at += 1;
2245 }
2246 (!text.is_empty()).then_some(value)
2247}
2248
2249fn decimal(text: &[u8]) -> Option<f64> {
2251 core::str::from_utf8(text).ok()?.parse::<f64>().ok()
2252}
2253
2254fn number(words: &[Word], letter: char) -> Option<f64> {
2257 let mut at = 0;
2258 while at < words.len() {
2259 let Word {
2260 letter: word,
2261 value,
2262 } = words[at];
2263 if char::from(word) == letter {
2264 return Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
2265 }
2266 at += 1;
2267 }
2268 None
2269}
2270
2271#[must_use]
2274pub fn index_of(pieces: &[&[u8]]) -> GcodeIndex {
2275 let mut builder = IndexBuilder::new();
2276 for piece in pieces {
2277 let _ = builder.take(piece);
2278 }
2279 builder.finish()
2280}
2281
2282#[derive(Debug, Default)]
2284enum Slot {
2285 #[default]
2287 Empty,
2288 Building(Vec<Waker>),
2290 Ready(Arc<GcodeIndex>),
2292}
2293
2294#[derive(Debug, Default)]
2296pub struct GcodeIndexes {
2297 slots: Mutex<BTreeMap<PrintId, Slot>>,
2299 looked: Mutex<BTreeMap<PrintId, Vec<(Timestamp, i64)>>>,
2305}
2306
2307#[derive(Debug)]
2309pub enum Claimed<'a> {
2310 Ready(Arc<GcodeIndex>),
2312 Build(BuildClaim<'a>),
2314}
2315
2316#[derive(Debug)]
2319pub struct BuildClaim<'a> {
2320 indexes: &'a GcodeIndexes,
2322 print_id: PrintId,
2324 done: bool,
2326}
2327
2328impl BuildClaim<'_> {
2329 #[must_use]
2331 pub fn finish(mut self, index: GcodeIndex) -> Arc<GcodeIndex> {
2332 let index = Arc::new(index);
2333 self.settle(Slot::Ready(Arc::clone(&index)));
2334 self.done = true;
2335 index
2336 }
2337
2338 fn settle(&self, next: Slot) {
2340 let waiting = {
2341 let mut slots = self.indexes.held();
2342 let slot = slots.entry(self.print_id).or_default();
2343 match core::mem::replace(slot, next) {
2344 Slot::Building(waiting) => waiting,
2345 Slot::Empty | Slot::Ready(_) => Vec::new(),
2346 }
2347 };
2348 for waker in waiting {
2349 waker.wake();
2350 }
2351 }
2352}
2353
2354impl Drop for BuildClaim<'_> {
2355 fn drop(&mut self) {
2356 if !self.done {
2357 self.settle(Slot::Empty);
2358 }
2359 }
2360}
2361
2362impl GcodeIndexes {
2363 fn held(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, Slot>> {
2365 self.slots.lock().unwrap_or_else(PoisonError::into_inner)
2366 }
2367
2368 pub const fn claim(&self, print_id: PrintId) -> Claim<'_> {
2371 Claim {
2372 indexes: self,
2373 print_id,
2374 }
2375 }
2376
2377 #[must_use]
2379 pub fn built(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
2380 match self.held().get(&print_id) {
2381 Some(Slot::Ready(index)) => Some(Arc::clone(index)),
2382 _ => None,
2383 }
2384 }
2385}
2386
2387#[derive(Debug)]
2389pub struct Claim<'a> {
2390 indexes: &'a GcodeIndexes,
2392 print_id: PrintId,
2394}
2395
2396impl<'a> Future for Claim<'a> {
2397 type Output = Claimed<'a>;
2398
2399 fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
2400 let mut slots = self.indexes.held();
2401 let slot = slots.entry(self.print_id).or_default();
2402 match slot {
2403 Slot::Ready(index) => Poll::Ready(Claimed::Ready(Arc::clone(index))),
2404 Slot::Building(waiting) => {
2405 if !waiting.iter().any(|held| held.will_wake(context.waker())) {
2406 waiting.push(context.waker().clone());
2407 }
2408 Poll::Pending
2409 }
2410 Slot::Empty => {
2411 *slot = Slot::Building(Vec::new());
2412 Poll::Ready(Claimed::Build(BuildClaim {
2413 indexes: self.indexes,
2414 print_id: self.print_id,
2415 done: false,
2416 }))
2417 }
2418 }
2419 }
2420}
2421
2422const HELD_INDEXES: usize = 16;
2426
2427impl GcodeIndexes {
2428 pub(crate) fn note_look(
2434 &self,
2435 print_id: PrintId,
2436 captured: Timestamp,
2437 position: i64,
2438 now: Timestamp,
2439 ) {
2440 let mut looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
2441 let frames = looked.entry(print_id).or_default();
2442 frames.push((captured, position));
2443 frames.sort_by_key(|(captured, _)| *captured);
2444 if let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) {
2445 let aged = frames.partition_point(|(captured, _)| *captured <= until);
2446 frames.drain(..aged.saturating_sub(1));
2447 }
2448 while looked.len() > HELD_INDEXES {
2449 let Some(oldest) = looked.keys().next().copied() else {
2450 break;
2451 };
2452 let _ = looked.remove(&oldest);
2453 }
2454 }
2455
2456 fn newest_look_until(&self, print_id: PrintId, until: Timestamp) -> Option<(Timestamp, i64)> {
2459 let looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
2460 looked
2461 .get(&print_id)?
2462 .iter()
2463 .rev()
2464 .find(|(captured, _)| *captured <= until)
2465 .copied()
2466 }
2467
2468 fn trim(&self, keep: PrintId) {
2470 let mut slots = self.held();
2471 let ready: Vec<PrintId> = slots
2472 .iter()
2473 .filter(|(print_id, slot)| **print_id != keep && matches!(slot, Slot::Ready(_)))
2474 .map(|(print_id, _)| *print_id)
2475 .collect();
2476 let over = slots.len().saturating_sub(HELD_INDEXES);
2477 for print_id in ready.into_iter().take(over) {
2478 slots.remove(&print_id);
2479 }
2480 }
2481}
2482
2483impl crate::supervisor::Supervisor {
2484 pub(crate) async fn slicer_plan(
2496 &self,
2497 print: &crate::records::PrintRecord,
2498 job: Option<&printobserver_printer_api::JobSnapshot>,
2499 interventions: &[crate::records::Intervention],
2500 ) -> Result<Option<SlicerPlan>, crate::error::CoreError> {
2501 let Some((position, file)) = job
2502 .and_then(|job| job.file_position_bytes.zip(job.file_name.as_deref()))
2503 .filter(|(_, file)| {
2504 print.ended_at.is_none() && print.file_name.as_deref() == Some(*file)
2505 })
2506 else {
2507 return Ok(None);
2508 };
2509 let Some(index) = self.index_of(print.id, file).await else {
2510 return Ok(None);
2511 };
2512 let (flow, fan) = self
2513 .changes_since(print.id, &index, position, interventions)
2514 .await?;
2515 let mut plan = index.plan_with(position, flow, fan);
2516 plan.change_waiting = self
2517 .planned_change_waiting(print.id)
2518 .await?
2519 .map(|waiting| waiting.reached.change);
2520 plan.rise = self.rise_of(print.id, &index, position).await?;
2521 if plan.rise.is_none() {
2522 plan.unknown.push(PlanFact::Rise);
2523 plan.unknown.sort_unstable();
2524 }
2525 Ok(Some(plan))
2526 }
2527
2528 async fn rise_of(
2533 &self,
2534 print_id: PrintId,
2535 index: &GcodeIndex,
2536 position: i64,
2537 ) -> Result<Option<Rise>, crate::error::CoreError> {
2538 use printobserver_types::EventPayload as _;
2539
2540 use crate::kinds::PeriodicObservationPayload;
2541
2542 let now = self.clock().now();
2543 let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) else {
2544 return Ok(None);
2545 };
2546 let events = self
2547 .stores()
2548 .events
2549 .history(crate::store::HistoryQuery {
2550 print_id,
2551 kinds: printobserver_types::EventKind::new(PeriodicObservationPayload::KIND)
2552 .into_iter()
2553 .collect(),
2554 since: None,
2555 until: Some(until),
2556 limit: Some(1),
2557 })
2558 .await?;
2559 let observed = events.first().and_then(|event| {
2560 let observed = event.payload_as::<PeriodicObservationPayload>()?.ok()?;
2561 let earlier = observed.job?.file_position_bytes?;
2562 Some((
2563 observed.frame_captured_at.unwrap_or(event.received_at),
2564 earlier,
2565 ))
2566 });
2567 let looked = self.gcode_indexes().newest_look_until(print_id, until);
2568 let newest = match (observed, looked) {
2569 (Some(observed), Some(looked)) => Some(if looked.0 > observed.0 {
2570 looked
2571 } else {
2572 observed
2573 }),
2574 (observed, looked) => observed.or(looked),
2575 };
2576 Ok(newest.and_then(|(since, earlier)| {
2577 Some(Rise {
2578 since,
2579 mm: index.height_and_rise_since(earlier, position)?,
2580 })
2581 }))
2582 }
2583
2584 pub async fn print_gcode_index(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
2589 let print = self.stores().prints.print(print_id).await.ok()??;
2596 if print.ended_at.is_some() {
2597 return None;
2598 }
2599 self.index_of(print.id, print.file_name.as_deref()?).await
2600 }
2601
2602 pub(crate) fn drop_gcode_spool(&self, print_id: PrintId) {
2604 if let Some(directory) = self.config().gcode_spool_dir.as_deref() {
2605 let _ = std::fs::remove_file(crate::toolpath::spool_path(directory, print_id));
2606 }
2607 }
2608
2609 pub async fn sweep_gcode_spools(&self) -> Result<(), crate::error::CoreError> {
2616 let Some(directory) = self.config().gcode_spool_dir.clone() else {
2617 return Ok(());
2618 };
2619 let open: Vec<String> = self
2620 .stores()
2621 .prints
2622 .open_prints()
2623 .await?
2624 .iter()
2625 .map(|print| print.id.to_string())
2626 .collect();
2627 let Ok(entries) = std::fs::read_dir(&directory) else {
2635 return Ok(());
2636 };
2637 for entry in entries.flatten() {
2638 let name = entry.file_name();
2639 let Some(print) = name
2641 .to_str()
2642 .and_then(|name| name.strip_suffix(crate::toolpath::SPOOL_SUFFIX))
2643 .filter(|print| print.parse::<PrintId>().is_ok())
2644 else {
2645 continue;
2646 };
2647 if !open.iter().any(|id| id == print) {
2648 let _ = std::fs::remove_file(entry.path());
2649 }
2650 }
2651 Ok(())
2652 }
2653
2654 async fn index_of(&self, print_id: PrintId, file: &str) -> Option<Arc<GcodeIndex>> {
2656 let file_name = printobserver_types::FileName::new(file).ok()?;
2658 let claim = match self.gcode_indexes().claim(print_id).await {
2659 Claimed::Ready(index) => return Some(index),
2660 Claimed::Build(claim) => claim,
2661 };
2662 let mut builder = self
2665 .config()
2666 .gcode_spool_dir
2667 .as_deref()
2668 .and_then(|directory| {
2669 IndexBuilder::spooling(crate::toolpath::spool_path(directory, print_id)).ok()
2670 })
2671 .unwrap_or_default();
2672 self.read_gcode(file_name.clone(), &mut builder)
2673 .await
2674 .ok()?;
2675 let index = claim.finish(builder.finish());
2676 self.gcode_indexes().trim(print_id);
2677 if let Ok(body) = printobserver_types::EventBody::of(&crate::kinds::GcodeIndexedPayload {
2678 file_name,
2679 bytes: index.bytes(),
2680 layers: u64::try_from(index.layer_count()).unwrap_or(u64::MAX),
2681 }) {
2682 let _ = self.append_system_event(print_id, body).await;
2685 }
2686 Some(index)
2687 }
2688
2689 async fn changes_since(
2698 &self,
2699 print_id: PrintId,
2700 index: &GcodeIndex,
2701 position: i64,
2702 interventions: &[crate::records::Intervention],
2703 ) -> Result<(Option<f64>, Option<f64>), crate::error::CoreError> {
2704 use printobserver_types::EventPayload as _;
2705
2706 use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload};
2707 use crate::records::PrintAction;
2708
2709 let kinds = [ActionRequestedPayload::KIND, ActionExecutedPayload::KIND]
2710 .iter()
2711 .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
2712 .collect();
2713 let events = self
2714 .stores()
2715 .events
2716 .history(crate::store::HistoryQuery {
2717 print_id,
2718 kinds,
2719 since: None,
2720 until: None,
2721 limit: Some(crate::store::MAX_HISTORY_LIMIT),
2722 })
2723 .await?;
2724 let requested: BTreeMap<crate::records::ActionId, PrintAction> = events
2725 .iter()
2726 .filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
2727 .filter_map(Result::ok)
2728 .map(|payload| (payload.action_id, payload.action))
2729 .collect();
2730 let mut flow = None;
2731 let mut fan = None;
2732 for executed in events
2734 .iter()
2735 .filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
2736 .filter_map(Result::ok)
2737 {
2738 let standing = executed
2739 .intervention_id
2740 .is_none_or(|opened| interventions.iter().any(|active| active.id == opened));
2741 let made = executed
2744 .file_position_bytes
2745 .and_then(|made| u64::try_from(made).ok())
2746 .unwrap_or(0);
2747 let after = |set: Option<SetInFile>| set.is_none_or(|set| made >= set.at);
2748 match requested.get(&executed.action_id) {
2749 Some(PrintAction::SetFlowrateFactor { factor, .. }) if flow.is_none() => {
2750 flow = Some((standing && after(index.flow_at(position))).then_some(*factor));
2751 }
2752 Some(PrintAction::SetFanPercent { percent, .. }) if fan.is_none() => {
2753 fan = Some((standing && after(index.fan_at(position))).then_some(*percent));
2754 }
2755 _ => {}
2756 }
2757 }
2758 Ok((flow.flatten(), fan.flatten()))
2759 }
2760}
2761
2762#[cfg(test)]
2763mod tests {
2764 use super::{GcodeIndexes, HELD_INDEXES, OVER_AIR, RISE_WINDOW_S, SUPPORTS, WALLS};
2765 use crate::toolpath::ExtrusionKind;
2766
2767 #[test]
2771 fn the_plans_type_names_map_to_the_kinds_the_toolpath_draws() {
2772 for name in WALLS {
2773 assert_eq!(ExtrusionKind::of_type(name), ExtrusionKind::Wall, "{name}");
2774 }
2775 for name in SUPPORTS {
2776 assert_eq!(
2777 ExtrusionKind::of_type(name),
2778 ExtrusionKind::Support,
2779 "{name}"
2780 );
2781 }
2782 for name in OVER_AIR {
2783 assert!(
2784 matches!(
2785 ExtrusionKind::of_type(name),
2786 ExtrusionKind::Bridge | ExtrusionKind::Overhang
2787 ),
2788 "{name}"
2789 );
2790 }
2791 }
2792 use printobserver_types::{PrintId, Timestamp};
2793
2794 fn after(start: Timestamp, seconds: i64) -> Timestamp {
2796 start.plus_seconds(seconds).expect("an instant")
2797 }
2798
2799 fn held(indexes: &GcodeIndexes, print_id: PrintId) -> Vec<(Timestamp, i64)> {
2801 indexes
2802 .looked
2803 .lock()
2804 .expect("the looks are held")
2805 .get(&print_id)
2806 .cloned()
2807 .unwrap_or_default()
2808 }
2809
2810 #[test]
2813 fn the_newest_aged_look_is_kept_and_every_older_one_let_go() {
2814 let indexes = GcodeIndexes::default();
2815 let print = PrintId::new();
2816 let start = Timestamp::now();
2817 indexes.note_look(print, start, 10, start);
2818 indexes.note_look(print, after(start, 60), 20, after(start, 60));
2819 let now = after(start, 60 + RISE_WINDOW_S + 30);
2820 indexes.note_look(print, now, 30, now);
2821
2822 assert_eq!(
2823 held(&indexes, print),
2824 vec![(after(start, 60), 20), (now, 30)]
2825 );
2826 assert_eq!(
2827 indexes.newest_look_until(print, after(now, -RISE_WINDOW_S)),
2828 Some((after(start, 60), 20))
2829 );
2830 assert_eq!(indexes.newest_look_until(print, after(start, 30)), None);
2831 }
2832
2833 #[test]
2836 fn the_looks_of_prints_beyond_the_held_count_are_let_go_oldest_first() {
2837 let indexes = GcodeIndexes::default();
2838 let now = Timestamp::now();
2839 let mut prints: Vec<PrintId> = (0..=HELD_INDEXES).map(|_| PrintId::new()).collect();
2840 prints.sort_unstable();
2841 for print in &prints {
2842 indexes.note_look(*print, now, 1, now);
2843 }
2844
2845 assert!(held(&indexes, prints[0]).is_empty());
2846 for print in &prints[1..] {
2847 assert_eq!(held(&indexes, *print), vec![(now, 1)]);
2848 }
2849 }
2850}