1use core::future::Future;
58use core::ops::ControlFlow;
59use core::pin::Pin;
60use core::task::{Context, Poll, Waker};
61use std::collections::BTreeMap;
62use std::sync::{Arc, Mutex, PoisonError};
63
64use printobserver_printer_api::GcodeSink;
65use printobserver_types::contract::Sample;
66use printobserver_types::schemars::JsonSchema;
67use printobserver_types::serde::{Deserialize, Serialize};
68use printobserver_types::{PrintId, Timestamp};
69
70const LINE_LIMIT: usize = 4096;
75
76const TYPE_LIMIT: usize = 64;
79
80const RISE_WINDOW_S: i64 = 30 * 60;
83
84const LAYERS_SHOWN_BELOW: usize = 5;
87
88const FLOW_WELL_UNDER_ONE: f64 = 0.9;
90
91const OVER_AIR: [&str; 2] = ["Bridge infill", "Overhang perimeter"];
93
94const SUPPORTS: [&str; 2] = ["Support material", "Support material interface"];
96
97const WALLS: [&str; 2] = ["Perimeter", "External perimeter"];
99
100const OBJECT_LIMIT: usize = 1024;
102
103const AXIS_LIMIT: f64 = 1e4;
106
107const WORD_LIMIT: f64 = 1e7;
110
111const WORD_COUNT: usize = 8;
113
114const TRAVEL_MM: f64 = 1e-6;
116
117const NOT_THE_PART: &str = "Custom";
119
120const FAN_FULL: f64 = 255.0;
122
123#[derive(Debug, Clone, PartialEq)]
125struct Layer {
126 at: u64,
128 z_mm: Option<f64>,
130 types: u64,
133}
134
135#[derive(Debug, Clone, Copy, PartialEq)]
137struct Mark<T> {
138 at: u64,
140 value: T,
142}
143
144#[derive(Debug, Clone, Default, PartialEq)]
146struct ObjectDraft {
147 bounds: Option<[f64; 4]>,
149}
150
151#[derive(Debug, Clone, PartialEq)]
153pub struct GcodeIndex {
154 bytes: u64,
156 lines: u64,
158 layers: Vec<Layer>,
160 type_names: Vec<String>,
162 labelled_types: bool,
164 time_left: Vec<Mark<i64>>,
166 flow: Vec<Mark<f64>>,
168 fan: Vec<Mark<f64>>,
170 objects: Vec<BedArea>,
172 labelled_objects: bool,
174}
175
176#[derive(Debug, Clone, Copy, PartialEq)]
179pub struct SetInFile {
180 pub value: f64,
182 pub at: u64,
184}
185
186impl GcodeIndex {
187 #[must_use]
189 pub const fn bytes(&self) -> u64 {
190 self.bytes
191 }
192
193 #[must_use]
195 pub const fn lines(&self) -> u64 {
196 self.lines
197 }
198
199 #[must_use]
201 pub const fn layer_count(&self) -> usize {
202 self.layers.len()
203 }
204
205 #[must_use]
208 pub const fn entries(&self) -> usize {
209 self.layers.len()
210 + self.time_left.len()
211 + self.flow.len()
212 + self.fan.len()
213 + self.objects.len()
214 }
215
216 #[must_use]
219 pub fn resident_bytes(&self) -> usize {
220 let names: usize = self.type_names.iter().map(String::capacity).sum();
221 core::mem::size_of::<Self>()
222 + self.layers.capacity() * core::mem::size_of::<Layer>()
223 + self.type_names.capacity() * core::mem::size_of::<String>()
224 + names
225 + self.time_left.capacity() * core::mem::size_of::<Mark<i64>>()
226 + self.flow.capacity() * core::mem::size_of::<Mark<f64>>()
227 + self.fan.capacity() * core::mem::size_of::<Mark<f64>>()
228 + self.objects.capacity() * core::mem::size_of::<BedArea>()
229 }
230
231 #[must_use]
235 pub fn busiest_layer(&self) -> Option<(usize, i64)> {
236 self.layers
237 .iter()
238 .map(|layer| {
239 (
240 usize::try_from(layer.types.count_ones()).unwrap_or(usize::MAX),
241 i64::try_from(layer.at).unwrap_or(i64::MAX),
242 )
243 })
244 .reduce(|best, next| if next.0 > best.0 { next } else { best })
245 }
246
247 #[must_use]
249 pub fn flow_at(&self, position: i64) -> Option<SetInFile> {
250 last_at(&self.flow, position).map(|mark| SetInFile {
251 value: mark.value,
252 at: mark.at,
253 })
254 }
255
256 #[must_use]
259 pub fn fan_at(&self, position: i64) -> Option<SetInFile> {
260 last_at(&self.fan, position).map(|mark| SetInFile {
261 value: mark.value,
262 at: mark.at,
263 })
264 }
265
266 #[must_use]
269 pub fn plan_at(&self, position: i64) -> SlicerPlan {
270 self.plan_with(position, None, None)
271 }
272
273 #[must_use]
277 pub fn plan_with(
278 &self,
279 position: i64,
280 flow_changed: Option<f64>,
281 fan_changed: Option<f64>,
282 ) -> SlicerPlan {
283 let mut unknown = Vec::new();
284 let layer_index = self
285 .layers
286 .iter()
287 .rposition(|layer| reached(layer.at, position));
288 let final_z_mm = self.layers.last().and_then(|layer| layer.z_mm);
289 if self.layers.is_empty() {
290 unknown.push(PlanFact::Layer);
291 }
292 if final_z_mm.is_none() {
293 unknown.push(PlanFact::FinalZ);
294 }
295 if !self.labelled_types {
296 unknown.push(PlanFact::Types);
297 }
298 let types = layer_index.map_or_else(Vec::new, |index| {
299 let bits = self.layers[index].types;
300 self.type_names
301 .iter()
302 .enumerate()
303 .filter(|(bit, _)| bits & (1 << bit) != 0)
304 .map(|(_, name)| name.clone())
305 .collect()
306 });
307 let minutes_left = last_at(&self.time_left, position).map(|mark| mark.value);
308 if minutes_left.is_none() {
309 unknown.push(PlanFact::MinutesLeft);
310 }
311 let flow_factor = set_value(
312 self.flow_at(position).map(|set| set.value),
313 flow_changed,
314 PlanFact::FlowFactor,
315 &mut unknown,
316 );
317 let fan_percent = set_value(
318 self.fan_at(position).map(|set| set.value),
319 fan_changed,
320 PlanFact::FanPercent,
321 &mut unknown,
322 );
323 if !self.labelled_objects {
324 unknown.push(PlanFact::Objects);
325 }
326 unknown.sort_unstable();
327 let in_force =
328 |set: &Option<SetValue>| set.as_ref().and_then(|set| set.changed.or(set.file));
329 let mut at_odds = Vec::new();
330 if let Some(index) = layer_index {
331 let shown = self.layers[index.saturating_sub(LAYERS_SHOWN_BELOW)..=index]
332 .iter()
333 .fold(0, |bits, layer| bits | layer.types);
334 if in_force(&fan_percent).is_some_and(|fan| fan <= 0.0)
335 && shown & self.type_bits(&OVER_AIR) != 0
336 {
337 at_odds.push(PlanMismatch::FanOffOverBridges);
338 }
339 if in_force(&flow_factor).is_some_and(|flow| flow < FLOW_WELL_UNDER_ONE)
340 && self.layers[index].types & self.type_bits(&WALLS) != 0
341 {
342 at_odds.push(PlanMismatch::FlowLowOverWalls);
343 }
344 }
345 SlicerPlan {
346 layer: layer_index.map(|index| index + 1),
347 z_mm: layer_index.and_then(|index| self.layers[index].z_mm),
348 final_z_mm,
349 types,
350 minutes_left,
351 flow_factor,
352 fan_percent,
353 object_count: self.labelled_objects.then_some(self.objects.len()),
354 objects: self.objects.clone(),
355 rise: None,
356 at_odds,
357 unknown,
358 }
359 }
360
361 fn type_bits(&self, names: &[&str]) -> u64 {
363 self.type_names
364 .iter()
365 .enumerate()
366 .filter(|(_, name)| names.contains(&name.as_str()))
367 .fold(0, |bits, (bit, _)| bits | (1 << bit))
368 }
369
370 #[must_use]
379 pub fn risen_since(&self, earlier: i64, now: i64) -> Option<f64> {
380 self.height_and_rise_since(earlier, now)
381 .map(|[_, risen]| risen)
382 }
383
384 #[must_use]
388 pub fn height_and_rise_since(&self, earlier: i64, now: i64) -> Option<[f64; 2]> {
389 let at = |position| {
390 self.layers
391 .iter()
392 .rposition(|layer| reached(layer.at, position))
393 .filter(|index| self.layers[*index].z_mm.is_some())
394 };
395 let (then, now) = (at(earlier)?, at(now)?);
396 let supports = self.type_bits(&SUPPORTS);
397 let lays_the_part = |layer: &&Layer| layer.types & !supports != 0;
398 let mut top = self.layers[..=then]
401 .iter()
402 .rev()
403 .filter(lays_the_part)
404 .find_map(|layer| layer.z_mm)
405 .or(self.layers[then].z_mm)?;
406 let height = top;
407 let mut risen = 0.0;
408 for layer in self
409 .layers
410 .iter()
411 .take(now + 1)
412 .skip(then + 1)
413 .filter(lays_the_part)
414 {
415 let Some(z) = layer.z_mm else { continue };
416 risen += (z - top).max(0.0);
417 top = top.max(z);
418 }
419 let tenth = |mm: f64| (mm * 10.0).round() / 10.0;
420 Some([tenth(height), tenth(risen)])
421 }
422}
423
424fn set_value(
427 file: Option<f64>,
428 changed: Option<f64>,
429 fact: PlanFact,
430 unknown: &mut Vec<PlanFact>,
431) -> Option<SetValue> {
432 if file.is_none() {
433 unknown.push(fact);
434 }
435 (file.is_some() || changed.is_some()).then_some(SetValue { file, changed })
436}
437
438fn reached(at: u64, position: i64) -> bool {
440 u64::try_from(position).is_ok_and(|position| at <= position)
441}
442
443fn last_at<T: Copy>(marks: &[Mark<T>], position: i64) -> Option<Mark<T>> {
445 let Ok(position) = u64::try_from(position) else {
446 return None;
447 };
448 let reached = marks.partition_point(|mark| mark.at <= position);
449 reached.checked_sub(1).map(|index| marks[index])
450}
451
452#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
455#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
456#[schemars(crate = "printobserver_types::schemars")]
457pub struct SetValue {
458 #[serde(default, skip_serializing_if = "Option::is_none")]
460 pub file: Option<f64>,
461 #[serde(default, skip_serializing_if = "Option::is_none")]
464 pub changed: Option<f64>,
465}
466
467pub type BedArea = [i64; 4];
472
473#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
476#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
477#[schemars(crate = "printobserver_types::schemars")]
478pub struct Rise {
479 pub since: Timestamp,
483 pub mm: [f64; 2],
489}
490
491#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
494#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
495#[schemars(crate = "printobserver_types::schemars")]
496pub enum PlanMismatch {
497 FanOffOverBridges,
500 FlowLowOverWalls,
502}
503
504#[derive(
506 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
507)]
508#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
509#[schemars(crate = "printobserver_types::schemars")]
510pub enum PlanFact {
511 Layer,
513 FinalZ,
515 Types,
517 MinutesLeft,
519 FlowFactor,
521 FanPercent,
523 Objects,
525 Rise,
529}
530
531#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
538#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
539#[schemars(crate = "printobserver_types::schemars")]
540pub struct SlicerPlan {
541 #[serde(default, skip_serializing_if = "Option::is_none")]
544 pub layer: Option<usize>,
545 #[serde(default, skip_serializing_if = "Option::is_none")]
547 pub z_mm: Option<f64>,
548 #[serde(default, skip_serializing_if = "Option::is_none")]
550 pub final_z_mm: Option<f64>,
551 #[serde(default, skip_serializing_if = "Vec::is_empty")]
554 pub types: Vec<String>,
555 #[serde(default, skip_serializing_if = "Option::is_none")]
557 pub minutes_left: Option<i64>,
558 #[serde(default, skip_serializing_if = "Option::is_none")]
560 pub flow_factor: Option<SetValue>,
561 #[serde(default, skip_serializing_if = "Option::is_none")]
563 pub fan_percent: Option<SetValue>,
564 #[serde(default, skip_serializing_if = "Option::is_none")]
566 pub object_count: Option<usize>,
567 #[serde(default, skip_serializing_if = "Vec::is_empty")]
571 pub objects: Vec<BedArea>,
572 #[serde(default, skip_serializing_if = "Option::is_none")]
575 pub rise: Option<Rise>,
576 #[serde(default, skip_serializing_if = "Vec::is_empty")]
578 pub at_odds: Vec<PlanMismatch>,
579 #[serde(default, skip_serializing_if = "Vec::is_empty")]
582 pub unknown: Vec<PlanFact>,
583}
584
585impl Sample for SlicerPlan {
586 fn sample_full() -> Self {
587 Self {
588 layer: Some(12),
589 z_mm: Some(2.4),
590 types: vec![
591 "Perimeter".to_owned(),
592 "External perimeter".to_owned(),
593 "Support material".to_owned(),
594 ],
595 final_z_mm: Some(30.0),
596 minutes_left: Some(42),
597 flow_factor: Some(SetValue {
598 file: Some(1.0),
599 changed: Some(0.95),
600 }),
601 fan_percent: Some(SetValue {
602 file: Some(100.0),
603 changed: None,
604 }),
605 object_count: Some(1),
606 objects: vec![[100, 99, 150, 117]],
607 rise: Some(Rise {
608 since: Timestamp::sample_full(),
609 mm: [7.2, 4.8],
610 }),
611 at_odds: vec![PlanMismatch::FlowLowOverWalls],
612 unknown: vec![PlanFact::Objects],
613 }
614 }
615
616 fn sample_minimal() -> Self {
617 Self {
618 layer: None,
619 z_mm: None,
620 final_z_mm: None,
621 types: Vec::new(),
622 minutes_left: None,
623 flow_factor: None,
624 fan_percent: None,
625 object_count: None,
626 objects: Vec::new(),
627 rise: None,
628 at_odds: Vec::new(),
629 unknown: Vec::new(),
630 }
631 }
632}
633
634#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
636enum Positioning {
637 #[default]
639 Absolute,
640 Relative,
642}
643
644#[derive(Debug, Default)]
647pub struct IndexBuilder {
648 line: Vec<u8>,
650 overlong: bool,
652 read: u64,
654 lines: u64,
656 layers: Vec<Layer>,
658 type_names: Vec<String>,
660 labelled_types: bool,
662 current_type: Option<usize>,
664 time_left: Vec<Mark<i64>>,
666 flow: Vec<Mark<f64>>,
668 fan: Vec<Mark<f64>>,
670 objects: Vec<ObjectDraft>,
672 object_numbers: BTreeMap<i64, usize>,
674 current_object: Option<usize>,
677 labelled_objects: bool,
679 at: [f64; 3],
681 e: f64,
683 axes: Positioning,
685 extruder: Positioning,
687}
688
689impl GcodeSink for IndexBuilder {
690 fn take(&mut self, piece: &[u8]) -> ControlFlow<()> {
691 let mut start = 0;
695 let mut at = 0;
696 while at < piece.len() {
697 if piece[at] == b'\n' {
698 let head = &piece[start..at];
699 self.read += u64::try_from(at + 1 - start).unwrap_or(u64::MAX);
700 if self.line.is_empty() && !self.overlong {
701 self.lines += 1;
703 if head.len() <= LINE_LIMIT {
704 self.read_line(head);
705 }
706 } else {
707 self.hold(head);
708 self.end_line();
709 }
710 start = at + 1;
711 }
712 at += 1;
713 }
714 let rest = &piece[start..];
715 self.hold(rest);
716 self.read += u64::try_from(rest.len()).unwrap_or(u64::MAX);
717 ControlFlow::Continue(())
718 }
719}
720
721impl IndexBuilder {
722 #[must_use]
724 pub fn new() -> Self {
725 Self::default()
726 }
727
728 #[must_use]
731 pub fn finish(mut self) -> GcodeIndex {
732 if !self.line.is_empty() || self.overlong {
733 self.end_line();
734 }
735 let mut drafts: Vec<Option<ObjectDraft>> = self.objects.into_iter().map(Some).collect();
736 let objects = self
737 .object_numbers
738 .into_values()
739 .filter_map(|place| drafts.get_mut(place).and_then(Option::take))
740 .filter_map(|draft| {
741 draft.bounds.map(|[least_x, least_y, most_x, most_y]| {
742 [
743 whole(tenth(least_x).floor()),
744 whole(tenth(least_y).floor()),
745 whole(tenth(most_x).ceil()),
746 whole(tenth(most_y).ceil()),
747 ]
748 })
749 })
750 .collect();
751 GcodeIndex {
752 bytes: self.read,
753 lines: self.lines,
754 layers: self.layers,
755 type_names: self.type_names,
756 labelled_types: self.labelled_types,
757 time_left: self.time_left,
758 flow: self.flow,
759 fan: self.fan,
760 objects,
761 labelled_objects: self.labelled_objects,
762 }
763 }
764
765 fn hold(&mut self, bytes: &[u8]) {
767 if self.overlong {
768 return;
769 }
770 if self.line.len() + bytes.len() > LINE_LIMIT {
771 self.overlong = true;
772 self.line.clear();
773 return;
774 }
775 self.line.extend_from_slice(bytes);
776 }
777
778 fn end_line(&mut self) {
780 self.lines += 1;
781 let line = core::mem::take(&mut self.line);
782 if !self.overlong {
783 self.read_line(&line);
784 }
785 self.overlong = false;
786 self.line = line;
787 self.line.clear();
788 }
789
790 fn read_line(&mut self, raw: &[u8]) {
792 let raw = raw.trim_ascii();
793 if let Some(comment) = raw.strip_prefix(b";") {
794 if let Ok(comment) = core::str::from_utf8(comment) {
795 self.comment(comment.trim_end());
796 }
797 return;
798 }
799 if let [b'G', code @ b'0'..=b'3', b' ', rest @ ..] = raw {
802 self.motion(u32::from(code - b'0'), &move_of(rest));
803 return;
804 }
805 let held = words(raw);
806 let mut words = held.as_slice();
807 if let Some((Word { letter: b'N', .. }, rest)) = words.split_first() {
809 words = rest;
810 }
811 let Some(first) = words.first() else {
812 return;
813 };
814 let code = if held.numbered {
815 held.second_code
816 } else {
817 held.first_code
818 };
819 match (char::from(first.letter), code) {
820 ('G', Some(code @ 0..=3)) => self.motion(code, &Move::of(&words[1..])),
821 ('G', Some(28)) => self.home(&words[1..]),
822 ('G', Some(90)) => self.axes = Positioning::Absolute,
823 ('G', Some(91)) => self.axes = Positioning::Relative,
824 ('G', Some(92)) => self.declare(&words[1..]),
825 ('M', Some(82)) => self.extruder = Positioning::Absolute,
826 ('M', Some(83)) => self.extruder = Positioning::Relative,
827 ('M', Some(73)) => self.estimate(&words[1..]),
828 ('M', Some(221)) => self.flow_factor(&words[1..]),
829 ('M', Some(106)) => self.fan_speed(&words[1..], Fan::Set),
830 ('M', Some(107)) => self.fan_speed(&words[1..], Fan::Off),
831 ('M', Some(486)) => self.object(raw, &words[1..]),
832 _ => {}
833 }
834 }
835
836 fn comment(&mut self, comment: &str) {
838 if comment == "LAYER_CHANGE" {
839 self.layers.push(Layer {
840 at: self.read,
841 z_mm: None,
842 types: 0,
843 });
844 } else if let Some(z) = comment.strip_prefix("Z:") {
845 if let Some(layer) = self.layers.last_mut()
846 && layer.z_mm.is_none()
847 {
848 layer.z_mm = z
851 .trim()
852 .parse::<f64>()
853 .ok()
854 .filter(|z| (0.0..=AXIS_LIMIT).contains(z));
855 }
856 } else if let Some(name) = comment.strip_prefix("TYPE:") {
857 let name = name.trim();
858 self.labelled_types = true;
859 self.current_type = if name == NOT_THE_PART {
860 None
861 } else {
862 self.intern(name)
863 };
864 }
865 }
866
867 fn intern(&mut self, name: &str) -> Option<usize> {
869 if let Some(bit) = self.type_names.iter().position(|held| held == name) {
870 return Some(bit);
871 }
872 if self.type_names.len() >= TYPE_LIMIT {
873 return None;
874 }
875 self.type_names.push(name.to_owned());
876 Some(self.type_names.len() - 1)
877 }
878
879 fn motion(&mut self, code: u32, words: &Move) {
881 let start = self.at;
884 let relative = self.axes == Positioning::Relative;
885 if let Some(x) = words.x {
886 self.place(0, x, relative);
887 }
888 if let Some(y) = words.y {
889 self.place(1, y, relative);
890 }
891 if let Some(z) = words.z {
892 self.place(2, z, relative);
893 }
894 let mut fed = 0.0;
895 if let Some(value) = words.e {
896 if relative || self.extruder == Positioning::Relative {
897 self.e += value;
898 fed = value;
899 } else {
900 fed = value - self.e;
901 self.e = value;
902 }
903 }
904 let travel = (self.at[0] - start[0]).hypot(self.at[1] - start[1]);
905 if fed <= 0.0 || (travel <= TRAVEL_MM && code < 2) {
906 return;
907 }
908 if let (Some(layer), Some(bit)) = (self.layers.last_mut(), self.current_type) {
909 layer.types |= 1 << bit;
910 }
911 let Some(object) = self.current_object else {
912 return;
913 };
914 let end = self.at;
915 let draft = &mut self.objects[object];
916 grow(&mut draft.bounds, start[0], start[1]);
917 grow(&mut draft.bounds, end[0], end[1]);
918 if code >= 2 {
919 let turn = if code == 2 {
920 Turn::Clockwise
921 } else {
922 Turn::CounterClockwise
923 };
924 for [x, y] in arc_extremes(words, turn, start, end) {
925 grow(&mut draft.bounds, x, y);
926 }
927 }
928 }
929
930 fn place(&mut self, axis: usize, value: f64, relative: bool) {
934 let landed = if relative {
935 self.at[axis] + value
936 } else {
937 value
938 };
939 if landed.abs() <= AXIS_LIMIT {
940 self.at[axis] = landed;
941 }
942 }
943
944 fn home(&mut self, words: &[Word]) {
946 let named: Vec<usize> = ['X', 'Y', 'Z']
947 .into_iter()
948 .enumerate()
949 .filter(|(_, letter)| words.iter().any(|word| char::from(word.letter) == *letter))
950 .map(|(axis, _)| axis)
951 .collect();
952 if named.is_empty() {
953 self.at = [0.0; 3];
954 } else {
955 for axis in named {
956 self.at[axis] = 0.0;
957 }
958 }
959 }
960
961 fn declare(&mut self, words: &[Word]) {
964 if words.is_empty() {
965 self.at = [0.0; 3];
966 self.e = 0.0;
967 return;
968 }
969 for (axis, letter) in ['X', 'Y', 'Z'].into_iter().enumerate() {
970 if let Some(value) = number(words, letter).filter(|value| value.abs() <= AXIS_LIMIT) {
971 self.at[axis] = value;
972 }
973 }
974 if let Some(value) = number(words, 'E') {
975 self.e = value;
976 }
977 }
978
979 fn estimate(&mut self, words: &[Word]) {
981 if number(words, 'P').is_none() {
982 return;
983 }
984 if let Some(minutes) = number(words, 'R').filter(|minutes| *minutes >= 0.0) {
985 self.time_left.push(Mark {
986 at: self.read,
987 value: whole(minutes),
988 });
989 }
990 }
991
992 fn flow_factor(&mut self, words: &[Word]) {
994 if let Some(percent) = number(words, 'S').filter(|percent| *percent >= 0.0) {
995 mark_setting(&mut self.flow, self.read, percent / 100.0);
996 }
997 }
998
999 fn fan_speed(&mut self, words: &[Word], command: Fan) {
1001 if number(words, 'P').is_some_and(|fan| fan != 0.0) {
1002 return;
1003 }
1004 let speed = match command {
1005 Fan::Off => 0.0,
1006 Fan::Set => number(words, 'S').unwrap_or(FAN_FULL),
1007 };
1008 let percent = (speed.clamp(0.0, FAN_FULL) / FAN_FULL * 100.0).round();
1009 mark_setting(&mut self.fan, self.read, percent);
1010 }
1011
1012 fn object(&mut self, raw: &[u8], words: &[Word]) {
1014 if raw
1017 .strip_prefix(b"M486")
1018 .is_some_and(|rest| rest.trim_ascii_start().starts_with(b"A"))
1019 {
1020 self.labelled_objects = true;
1021 return;
1022 }
1023 let Some(number) = number(words, 'S')
1026 .filter(|number| (number - number.round()).abs() < f64::EPSILON && *number >= -1.0)
1027 else {
1028 return;
1029 };
1030 self.labelled_objects = true;
1031 if number < 0.0 {
1032 self.current_object = None;
1033 return;
1034 }
1035 let id = whole(number);
1036 let place = if let Some(place) = self.object_numbers.get(&id) {
1037 *place
1038 } else if self.objects.len() >= OBJECT_LIMIT {
1039 self.current_object = None;
1040 return;
1041 } else {
1042 self.objects.push(ObjectDraft::default());
1043 self.object_numbers.insert(id, self.objects.len() - 1);
1044 self.objects.len() - 1
1045 };
1046 self.current_object = Some(place);
1047 }
1048}
1049
1050fn mark_setting(marks: &mut Vec<Mark<f64>>, at: u64, value: f64) {
1054 marks.push(Mark { at, value });
1055}
1056
1057fn whole(value: f64) -> i64 {
1060 format!("{:.0}", value.round()).parse().unwrap_or_default()
1061}
1062
1063fn tenth(value: f64) -> f64 {
1067 (value * 10.0).round() / 10.0
1068}
1069
1070fn grow(bounds: &mut Option<[f64; 4]>, x: f64, y: f64) {
1072 *bounds = Some(match *bounds {
1073 None => [x, y, x, y],
1074 Some([least_x, least_y, most_x, most_y]) => {
1075 [least_x.min(x), least_y.min(y), most_x.max(x), most_y.max(y)]
1076 }
1077 });
1078}
1079
1080#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1082enum Turn {
1083 Clockwise,
1085 CounterClockwise,
1087}
1088
1089#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1092enum Fan {
1093 Set,
1095 Off,
1097}
1098
1099fn arc_extremes(
1108 words: &Move,
1109 turn: Turn,
1110 start: [f64; 3],
1111 end: [f64; 3],
1112) -> impl Iterator<Item = [f64; 2]> {
1113 let centre = words.r.map_or_else(
1114 || {
1115 Some([
1116 start[0] + words.i.unwrap_or(0.0),
1117 start[1] + words.j.unwrap_or(0.0),
1118 ])
1119 },
1120 |radius| centre_of_radius(radius, turn, start, end),
1121 );
1122 let reach = centre.map(|centre| {
1123 let radius = (start[0] - centre[0]).hypot(start[1] - centre[1]);
1124 let from = (start[1] - centre[1]).atan2(start[0] - centre[0]);
1125 let to = (end[1] - centre[1]).atan2(end[0] - centre[0]);
1126 let tau = core::f64::consts::TAU;
1127 let (base, sweep) = match turn {
1130 Turn::Clockwise => (to, (from - to).rem_euclid(tau)),
1131 Turn::CounterClockwise => (from, (to - from).rem_euclid(tau)),
1132 };
1133 let sweep = if sweep < 1e-9 { tau } else { sweep };
1134 (0..4).filter_map(move |quarter| {
1135 let angle = core::f64::consts::FRAC_PI_2 * f64::from(quarter);
1136 ((angle - base).rem_euclid(tau) <= sweep + 1e-9).then(|| {
1137 [
1138 centre[0] + radius * angle.cos(),
1139 centre[1] + radius * angle.sin(),
1140 ]
1141 })
1142 })
1143 });
1144 reach.into_iter().flatten()
1145}
1146
1147fn centre_of_radius(radius: f64, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<[f64; 2]> {
1152 let chord = [end[0] - start[0], end[1] - start[1]];
1153 let length = chord[0].hypot(chord[1]);
1154 if length <= TRAVEL_MM || length > 2.0 * radius.abs() {
1155 return None;
1156 }
1157 let rise = (radius * radius - length * length / 4.0).max(0.0).sqrt();
1158 let left = match turn {
1159 Turn::Clockwise => -1.0,
1160 Turn::CounterClockwise => 1.0,
1161 };
1162 let side = left * radius.signum() * rise / length;
1163 Some([
1164 start[0] + chord[0] / 2.0 - chord[1] * side,
1165 start[1] + chord[1] / 2.0 + chord[0] * side,
1166 ])
1167}
1168
1169fn words(command: &[u8]) -> Words {
1175 let mut found = Words {
1176 held: [Word {
1177 letter: 0,
1178 value: f64::NAN,
1179 }; WORD_COUNT],
1180 len: 0,
1181 first_code: None,
1182 second_code: None,
1183 numbered: false,
1184 };
1185 let length = command.len();
1186 let mut at = 0;
1187 while at < length {
1188 let letter = command[at];
1189 if letter == b';' || letter == b'*' {
1190 break;
1191 }
1192 at += 1;
1193 let upper = match letter {
1194 b'a'..=b'z' => letter - (b'a' - b'A'),
1195 b'A'..=b'Z' => letter,
1196 _ => continue,
1197 };
1198 let start = at;
1199 let (value, next) = number_at(command, at);
1200 at = next;
1201 let text = &command[start..at];
1202 if found.len == 0 {
1205 found.first_code = whole_number(text);
1206 found.numbered = upper == b'N';
1207 } else if found.len == 1 {
1208 found.second_code = whole_number(text);
1209 }
1210 if found.len < WORD_COUNT {
1211 found.held[found.len] = Word {
1212 letter: upper,
1213 value,
1214 };
1215 found.len += 1;
1216 }
1217 }
1218 found
1219}
1220
1221fn number_at(line: &[u8], mut at: usize) -> (f64, usize) {
1230 let start = at;
1231 while at < line.len()
1232 && !matches!(line[at], b' ' | b'\t' | b';' | b'*' | b'A'..=b'Z' | b'a'..=b'z')
1233 {
1234 at += 1;
1235 }
1236 (decimal(&line[start..at]).unwrap_or(f64::NAN), at)
1237}
1238
1239#[derive(Debug, Clone, Copy, Default)]
1243struct Move {
1244 x: Option<f64>,
1246 y: Option<f64>,
1248 z: Option<f64>,
1250 e: Option<f64>,
1252 i: Option<f64>,
1254 j: Option<f64>,
1256 r: Option<f64>,
1258}
1259
1260impl Move {
1261 fn of(words: &[Word]) -> Self {
1263 Self {
1264 x: number(words, 'X'),
1265 y: number(words, 'Y'),
1266 z: number(words, 'Z'),
1267 e: number(words, 'E'),
1268 i: number(words, 'I'),
1269 j: number(words, 'J'),
1270 r: number(words, 'R'),
1271 }
1272 }
1273}
1274
1275fn move_of(line: &[u8]) -> Move {
1280 let mut found = Move::default();
1281 let length = line.len();
1282 let mut at = 0;
1283 while at < length {
1284 let letter = line[at];
1285 at += 1;
1286 let slot = match letter {
1287 b';' | b'*' => break,
1288 b'X' | b'x' => &mut found.x,
1289 b'Y' | b'y' => &mut found.y,
1290 b'Z' | b'z' => &mut found.z,
1291 b'E' | b'e' => &mut found.e,
1292 b'I' | b'i' => &mut found.i,
1293 b'J' | b'j' => &mut found.j,
1294 b'R' | b'r' => &mut found.r,
1295 b'A'..=b'Z' | b'a'..=b'z' => {
1296 while at < length && !matches!(line[at], b' ' | b'\t' | b';' | b'*') {
1297 at += 1;
1298 }
1299 continue;
1300 }
1301 _ => continue,
1302 };
1303 let (value, next) = number_at(line, at);
1304 at = next;
1305 if slot.is_none() {
1306 *slot = Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
1307 }
1308 }
1309 found
1310}
1311
1312#[derive(Debug, Clone, Copy)]
1315struct Word {
1316 letter: u8,
1318 value: f64,
1320}
1321
1322struct Words {
1324 held: [Word; WORD_COUNT],
1326 len: usize,
1328 first_code: Option<u32>,
1330 second_code: Option<u32>,
1332 numbered: bool,
1334}
1335
1336impl Words {
1337 fn as_slice(&self) -> &[Word] {
1339 &self.held[..self.len]
1340 }
1341}
1342
1343fn whole_number(text: &[u8]) -> Option<u32> {
1345 let mut value: u32 = 0;
1346 let mut at = 0;
1347 while at < text.len() {
1348 let byte = text[at];
1349 if !byte.is_ascii_digit() {
1350 return None;
1351 }
1352 value = value.checked_mul(10)?.checked_add(u32::from(byte - b'0'))?;
1353 at += 1;
1354 }
1355 (!text.is_empty()).then_some(value)
1356}
1357
1358fn decimal(text: &[u8]) -> Option<f64> {
1360 core::str::from_utf8(text).ok()?.parse::<f64>().ok()
1361}
1362
1363fn number(words: &[Word], letter: char) -> Option<f64> {
1366 let mut at = 0;
1367 while at < words.len() {
1368 let Word {
1369 letter: word,
1370 value,
1371 } = words[at];
1372 if char::from(word) == letter {
1373 return Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
1374 }
1375 at += 1;
1376 }
1377 None
1378}
1379
1380#[must_use]
1383pub fn index_of(pieces: &[&[u8]]) -> GcodeIndex {
1384 let mut builder = IndexBuilder::new();
1385 for piece in pieces {
1386 let _ = builder.take(piece);
1387 }
1388 builder.finish()
1389}
1390
1391#[derive(Debug, Default)]
1393enum Slot {
1394 #[default]
1396 Empty,
1397 Building(Vec<Waker>),
1399 Ready(Arc<GcodeIndex>),
1401}
1402
1403#[derive(Debug, Default)]
1405pub struct GcodeIndexes {
1406 slots: Mutex<BTreeMap<PrintId, Slot>>,
1408 looked: Mutex<BTreeMap<PrintId, Vec<(Timestamp, i64)>>>,
1414}
1415
1416#[derive(Debug)]
1418pub enum Claimed<'a> {
1419 Ready(Arc<GcodeIndex>),
1421 Build(BuildClaim<'a>),
1423}
1424
1425#[derive(Debug)]
1428pub struct BuildClaim<'a> {
1429 indexes: &'a GcodeIndexes,
1431 print_id: PrintId,
1433 done: bool,
1435}
1436
1437impl BuildClaim<'_> {
1438 #[must_use]
1440 pub fn finish(mut self, index: GcodeIndex) -> Arc<GcodeIndex> {
1441 let index = Arc::new(index);
1442 self.settle(Slot::Ready(Arc::clone(&index)));
1443 self.done = true;
1444 index
1445 }
1446
1447 fn settle(&self, next: Slot) {
1449 let waiting = {
1450 let mut slots = self.indexes.held();
1451 let slot = slots.entry(self.print_id).or_default();
1452 match core::mem::replace(slot, next) {
1453 Slot::Building(waiting) => waiting,
1454 Slot::Empty | Slot::Ready(_) => Vec::new(),
1455 }
1456 };
1457 for waker in waiting {
1458 waker.wake();
1459 }
1460 }
1461}
1462
1463impl Drop for BuildClaim<'_> {
1464 fn drop(&mut self) {
1465 if !self.done {
1466 self.settle(Slot::Empty);
1467 }
1468 }
1469}
1470
1471impl GcodeIndexes {
1472 fn held(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, Slot>> {
1474 self.slots.lock().unwrap_or_else(PoisonError::into_inner)
1475 }
1476
1477 pub const fn claim(&self, print_id: PrintId) -> Claim<'_> {
1480 Claim {
1481 indexes: self,
1482 print_id,
1483 }
1484 }
1485
1486 #[must_use]
1488 pub fn built(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
1489 match self.held().get(&print_id) {
1490 Some(Slot::Ready(index)) => Some(Arc::clone(index)),
1491 _ => None,
1492 }
1493 }
1494}
1495
1496#[derive(Debug)]
1498pub struct Claim<'a> {
1499 indexes: &'a GcodeIndexes,
1501 print_id: PrintId,
1503}
1504
1505impl<'a> Future for Claim<'a> {
1506 type Output = Claimed<'a>;
1507
1508 fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
1509 let mut slots = self.indexes.held();
1510 let slot = slots.entry(self.print_id).or_default();
1511 match slot {
1512 Slot::Ready(index) => Poll::Ready(Claimed::Ready(Arc::clone(index))),
1513 Slot::Building(waiting) => {
1514 if !waiting.iter().any(|held| held.will_wake(context.waker())) {
1515 waiting.push(context.waker().clone());
1516 }
1517 Poll::Pending
1518 }
1519 Slot::Empty => {
1520 *slot = Slot::Building(Vec::new());
1521 Poll::Ready(Claimed::Build(BuildClaim {
1522 indexes: self.indexes,
1523 print_id: self.print_id,
1524 done: false,
1525 }))
1526 }
1527 }
1528 }
1529}
1530
1531const HELD_INDEXES: usize = 16;
1535
1536impl GcodeIndexes {
1537 pub(crate) fn note_look(
1543 &self,
1544 print_id: PrintId,
1545 captured: Timestamp,
1546 position: i64,
1547 now: Timestamp,
1548 ) {
1549 let mut looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
1550 let frames = looked.entry(print_id).or_default();
1551 frames.push((captured, position));
1552 frames.sort_by_key(|(captured, _)| *captured);
1553 if let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) {
1554 let aged = frames.partition_point(|(captured, _)| *captured <= until);
1555 frames.drain(..aged.saturating_sub(1));
1556 }
1557 while looked.len() > HELD_INDEXES {
1558 let Some(oldest) = looked.keys().next().copied() else {
1559 break;
1560 };
1561 let _ = looked.remove(&oldest);
1562 }
1563 }
1564
1565 fn newest_look_until(&self, print_id: PrintId, until: Timestamp) -> Option<(Timestamp, i64)> {
1568 let looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
1569 looked
1570 .get(&print_id)?
1571 .iter()
1572 .rev()
1573 .find(|(captured, _)| *captured <= until)
1574 .copied()
1575 }
1576
1577 fn trim(&self, keep: PrintId) {
1579 let mut slots = self.held();
1580 let ready: Vec<PrintId> = slots
1581 .iter()
1582 .filter(|(print_id, slot)| **print_id != keep && matches!(slot, Slot::Ready(_)))
1583 .map(|(print_id, _)| *print_id)
1584 .collect();
1585 let over = slots.len().saturating_sub(HELD_INDEXES);
1586 for print_id in ready.into_iter().take(over) {
1587 slots.remove(&print_id);
1588 }
1589 }
1590}
1591
1592impl crate::supervisor::Supervisor {
1593 pub(crate) async fn slicer_plan(
1605 &self,
1606 print: &crate::records::PrintRecord,
1607 job: Option<&printobserver_printer_api::JobSnapshot>,
1608 interventions: &[crate::records::Intervention],
1609 ) -> Result<Option<SlicerPlan>, crate::error::CoreError> {
1610 let Some((position, file)) = job
1611 .and_then(|job| job.file_position_bytes.zip(job.file_name.as_deref()))
1612 .filter(|(_, file)| {
1613 print.ended_at.is_none() && print.file_name.as_deref() == Some(*file)
1614 })
1615 else {
1616 return Ok(None);
1617 };
1618 let Some(index) = self.index_of(print.id, file).await else {
1619 return Ok(None);
1620 };
1621 let (flow, fan) = self
1622 .changes_since(print.id, &index, position, interventions)
1623 .await?;
1624 let mut plan = index.plan_with(position, flow, fan);
1625 plan.rise = self.rise_of(print.id, &index, position).await?;
1626 if plan.rise.is_none() {
1627 plan.unknown.push(PlanFact::Rise);
1628 plan.unknown.sort_unstable();
1629 }
1630 Ok(Some(plan))
1631 }
1632
1633 async fn rise_of(
1637 &self,
1638 print_id: PrintId,
1639 index: &GcodeIndex,
1640 position: i64,
1641 ) -> Result<Option<Rise>, crate::error::CoreError> {
1642 use printobserver_types::EventPayload as _;
1643
1644 use crate::kinds::PeriodicObservationPayload;
1645
1646 let now = self.clock().now();
1647 let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) else {
1648 return Ok(None);
1649 };
1650 let events = self
1651 .stores()
1652 .events
1653 .history(crate::store::HistoryQuery {
1654 print_id,
1655 kinds: printobserver_types::EventKind::new(PeriodicObservationPayload::KIND)
1656 .into_iter()
1657 .collect(),
1658 since: None,
1659 until: Some(until),
1660 limit: Some(1),
1661 })
1662 .await?;
1663 let observed = events.first().and_then(|event| {
1664 let observed = event.payload_as::<PeriodicObservationPayload>()?.ok()?;
1665 let earlier = observed.job?.file_position_bytes?;
1666 Some((
1667 observed.frame_captured_at.unwrap_or(event.received_at),
1668 earlier,
1669 ))
1670 });
1671 let looked = self.gcode_indexes().newest_look_until(print_id, until);
1672 let newest = match (observed, looked) {
1673 (Some(observed), Some(looked)) => Some(if looked.0 > observed.0 {
1674 looked
1675 } else {
1676 observed
1677 }),
1678 (observed, looked) => observed.or(looked),
1679 };
1680 Ok(newest.and_then(|(since, earlier)| {
1681 Some(Rise {
1682 since,
1683 mm: index.height_and_rise_since(earlier, position)?,
1684 })
1685 }))
1686 }
1687
1688 async fn index_of(&self, print_id: PrintId, file: &str) -> Option<Arc<GcodeIndex>> {
1690 let file_name = printobserver_types::FileName::new(file).ok()?;
1692 let claim = match self.gcode_indexes().claim(print_id).await {
1693 Claimed::Ready(index) => return Some(index),
1694 Claimed::Build(claim) => claim,
1695 };
1696 let mut builder = IndexBuilder::new();
1697 self.read_gcode(file_name.clone(), &mut builder)
1698 .await
1699 .ok()?;
1700 let index = claim.finish(builder.finish());
1701 self.gcode_indexes().trim(print_id);
1702 if let Ok(body) = printobserver_types::EventBody::of(&crate::kinds::GcodeIndexedPayload {
1703 file_name,
1704 bytes: index.bytes(),
1705 layers: u64::try_from(index.layer_count()).unwrap_or(u64::MAX),
1706 }) {
1707 let _ = self.append_system_event(print_id, body).await;
1710 }
1711 Some(index)
1712 }
1713
1714 async fn changes_since(
1723 &self,
1724 print_id: PrintId,
1725 index: &GcodeIndex,
1726 position: i64,
1727 interventions: &[crate::records::Intervention],
1728 ) -> Result<(Option<f64>, Option<f64>), crate::error::CoreError> {
1729 use printobserver_types::EventPayload as _;
1730
1731 use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload};
1732 use crate::records::PrintAction;
1733
1734 let kinds = [ActionRequestedPayload::KIND, ActionExecutedPayload::KIND]
1735 .iter()
1736 .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
1737 .collect();
1738 let events = self
1739 .stores()
1740 .events
1741 .history(crate::store::HistoryQuery {
1742 print_id,
1743 kinds,
1744 since: None,
1745 until: None,
1746 limit: Some(crate::store::MAX_HISTORY_LIMIT),
1747 })
1748 .await?;
1749 let requested: BTreeMap<crate::records::ActionId, PrintAction> = events
1750 .iter()
1751 .filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
1752 .filter_map(Result::ok)
1753 .map(|payload| (payload.action_id, payload.action))
1754 .collect();
1755 let mut flow = None;
1756 let mut fan = None;
1757 for executed in events
1759 .iter()
1760 .filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
1761 .filter_map(Result::ok)
1762 {
1763 let standing = executed
1764 .intervention_id
1765 .is_none_or(|opened| interventions.iter().any(|active| active.id == opened));
1766 let made = executed
1769 .file_position_bytes
1770 .and_then(|made| u64::try_from(made).ok())
1771 .unwrap_or(0);
1772 let after = |set: Option<SetInFile>| set.is_none_or(|set| made >= set.at);
1773 match requested.get(&executed.action_id) {
1774 Some(PrintAction::SetFlowrateFactor { factor, .. }) if flow.is_none() => {
1775 flow = Some((standing && after(index.flow_at(position))).then_some(*factor));
1776 }
1777 Some(PrintAction::SetFanPercent { percent, .. }) if fan.is_none() => {
1778 fan = Some((standing && after(index.fan_at(position))).then_some(*percent));
1779 }
1780 _ => {}
1781 }
1782 }
1783 Ok((flow.flatten(), fan.flatten()))
1784 }
1785}
1786
1787#[cfg(test)]
1788mod tests {
1789 use super::{GcodeIndexes, HELD_INDEXES, RISE_WINDOW_S};
1790 use printobserver_types::{PrintId, Timestamp};
1791
1792 fn after(start: Timestamp, seconds: i64) -> Timestamp {
1794 start.plus_seconds(seconds).expect("an instant")
1795 }
1796
1797 fn held(indexes: &GcodeIndexes, print_id: PrintId) -> Vec<(Timestamp, i64)> {
1799 indexes
1800 .looked
1801 .lock()
1802 .expect("the looks are held")
1803 .get(&print_id)
1804 .cloned()
1805 .unwrap_or_default()
1806 }
1807
1808 #[test]
1811 fn the_newest_aged_look_is_kept_and_every_older_one_let_go() {
1812 let indexes = GcodeIndexes::default();
1813 let print = PrintId::new();
1814 let start = Timestamp::now();
1815 indexes.note_look(print, start, 10, start);
1816 indexes.note_look(print, after(start, 60), 20, after(start, 60));
1817 let now = after(start, 60 + RISE_WINDOW_S + 30);
1818 indexes.note_look(print, now, 30, now);
1819
1820 assert_eq!(
1821 held(&indexes, print),
1822 vec![(after(start, 60), 20), (now, 30)]
1823 );
1824 assert_eq!(
1825 indexes.newest_look_until(print, after(now, -RISE_WINDOW_S)),
1826 Some((after(start, 60), 20))
1827 );
1828 assert_eq!(indexes.newest_look_until(print, after(start, 30)), None);
1829 }
1830
1831 #[test]
1834 fn the_looks_of_prints_beyond_the_held_count_are_let_go_oldest_first() {
1835 let indexes = GcodeIndexes::default();
1836 let now = Timestamp::now();
1837 let mut prints: Vec<PrintId> = (0..=HELD_INDEXES).map(|_| PrintId::new()).collect();
1838 prints.sort_unstable();
1839 for print in &prints {
1840 indexes.note_look(*print, now, 1, now);
1841 }
1842
1843 assert!(held(&indexes, prints[0]).is_empty());
1844 for print in &prints[1..] {
1845 assert_eq!(held(&indexes, *print), vec![(now, 1)]);
1846 }
1847 }
1848}