printobserver_server/
watch.rs1use std::collections::VecDeque;
35use std::future::poll_fn;
36use std::sync::atomic::{AtomicBool, Ordering};
37use std::sync::{Arc, Mutex, Weak};
38use std::time::{Duration, Instant};
39
40use printobserver_core::{
41 DetectorProbe, HeadPosition, PendingTurn, PositionProbe, Supervisor, block_on,
42};
43use printobserver_printer_api::{BoxFuture, PrinterCommand, PrinterPort, PrinterPush};
44
45use crate::alignment::Alignments;
46use tokio::task::JoinHandle;
47
48pub const REOPEN_AFTER: Duration = Duration::from_secs(5);
51
52pub const POSITION_WAIT: Duration = Duration::from_secs(3);
54
55const KEPT_LINES: usize = 64;
57
58#[derive(Debug)]
60pub struct Watching {
61 tasks: Vec<JoinHandle<()>>,
63}
64
65impl Watching {
66 pub fn abort(&self) {
68 for task in &self.tasks {
69 task.abort();
70 }
71 }
72}
73
74impl Drop for Watching {
75 fn drop(&mut self) {
76 self.abort();
77 }
78}
79
80#[derive(Debug, Default)]
82struct Terminal {
83 open: AtomicBool,
85 lines: Mutex<VecDeque<String>>,
87}
88
89impl Terminal {
90 fn keep(&self, line: String) {
92 let mut lines = self
93 .lines
94 .lock()
95 .unwrap_or_else(std::sync::PoisonError::into_inner);
96 lines.push_back(line);
97 while lines.len() > KEPT_LINES {
98 lines.pop_front();
99 }
100 }
101
102 fn take(&self) -> Vec<String> {
104 self.lines
105 .lock()
106 .unwrap_or_else(std::sync::PoisonError::into_inner)
107 .drain(..)
108 .collect()
109 }
110}
111
112struct Probe {
115 printer: Arc<dyn PrinterPort>,
117 terminal: Arc<Terminal>,
119}
120
121impl Probe {
122 async fn position(&self) -> Option<HeadPosition> {
124 if !self.terminal.open.load(Ordering::SeqCst) {
125 return None;
126 }
127 let _ = self.terminal.take();
129 self.printer
130 .send_command(PrinterCommand::ReportPosition)
131 .await
132 .ok()?;
133 let deadline = Instant::now() + POSITION_WAIT;
134 while Instant::now() < deadline {
135 let found = self
136 .terminal
137 .take()
138 .iter()
139 .find_map(|line| printobserver_octoprint::push::position_of(line));
140 if let Some([x, y, z]) = found {
141 return Some(HeadPosition { x, y, z });
142 }
143 std::thread::sleep(Duration::from_millis(50));
146 }
147 None
148 }
149}
150
151impl PositionProbe for Probe {
152 fn read_position(&self) -> BoxFuture<'_, Option<HeadPosition>> {
153 Box::pin(self.position())
154 }
155}
156
157pub fn start(
160 supervisor: &Arc<Supervisor>,
161 printer: Arc<dyn PrinterPort>,
162 detector: Option<Arc<dyn DetectorProbe>>,
163 alignments: Arc<Alignments>,
164) -> Watching {
165 let terminal = Arc::new(Terminal::default());
166 let probe = Arc::new(Probe {
167 printer: Arc::clone(&printer),
168 terminal: Arc::clone(&terminal),
169 });
170 let mut tasks = vec![
171 reading(Arc::downgrade(supervisor), probe, alignments),
172 pushing(Arc::downgrade(supervisor), printer, terminal),
173 ];
174 if let Some(detector) = detector {
175 tasks.push(checking(Arc::downgrade(supervisor), detector));
176 }
177 Watching { tasks }
178}
179
180fn run_turns(supervisor: &Arc<Supervisor>, turns: Vec<PendingTurn>) {
182 for turn in turns {
183 let runner = Arc::clone(supervisor);
184 tokio::spawn(async move {
185 let supervised = tokio::task::spawn_blocking(move || {
186 let _ = block_on(runner.run_supervision(turn));
187 })
188 .await;
189 debug_assert!(supervised.is_ok(), "one watch turn panicked");
190 });
191 }
192}
193
194fn reading(
197 weak: Weak<Supervisor>,
198 probe: Arc<Probe>,
199 alignments: Arc<Alignments>,
200) -> JoinHandle<()> {
201 tokio::spawn(async move {
202 loop {
203 let Some(poll) = weak.upgrade().map(|held| held.config().printer_poll) else {
204 return;
205 };
206 tokio::time::sleep(poll).await;
207 let Some(supervisor) = weak.upgrade() else {
208 return;
209 };
210 let watching = Arc::clone(&supervisor);
211 let probing = Arc::clone(&probe);
212 let watched = tokio::task::spawn_blocking(move || {
213 block_on(watching.watch_printer(probing.as_ref()))
214 })
215 .await;
216 if let Ok(Ok(watched)) = watched {
219 run_turns(&supervisor, watched.turns);
220 let held = Arc::clone(&alignments);
221 let _ = tokio::task::spawn_blocking(move || block_on(held.sweep())).await;
224 }
225 }
226 })
227}
228
229fn pushing(
231 weak: Weak<Supervisor>,
232 printer: Arc<dyn PrinterPort>,
233 terminal: Arc<Terminal>,
234) -> JoinHandle<()> {
235 tokio::spawn(async move {
236 loop {
237 let opening = Arc::clone(&printer);
238 let opened = tokio::task::spawn_blocking(move || block_on(opening.push_events())).await;
239 let Some(supervisor) = weak.upgrade() else {
240 return;
241 };
242 match opened {
243 Ok(Ok(mut stream)) => {
244 terminal.open.store(true, Ordering::SeqCst);
245 supervisor.note_push_channel(Ok(()));
246 drop(supervisor);
247 while let Some(push) =
248 poll_fn(|context| stream.as_mut().poll_next(context)).await
249 {
250 match push {
251 PrinterPush::Log { line } => terminal.keep(line),
252 other => {
253 let Some(supervisor) = weak.upgrade() else {
254 return;
255 };
256 let noted = tokio::task::spawn_blocking(move || {
257 block_on(supervisor.note_push(other))
258 })
259 .await;
260 debug_assert!(noted.is_ok(), "noting one push panicked");
261 }
262 }
263 }
264 terminal.open.store(false, Ordering::SeqCst);
265 let Some(supervisor) = weak.upgrade() else {
266 return;
267 };
268 supervisor.note_push_channel(Err("the push channel dropped".to_owned()));
269 }
270 Ok(Err(error)) => {
271 terminal.open.store(false, Ordering::SeqCst);
272 supervisor.note_push_channel(Err(error.to_string()));
273 }
274 Err(_) => {
275 terminal.open.store(false, Ordering::SeqCst);
276 supervisor
277 .note_push_channel(Err("opening the push channel panicked".to_owned()));
278 }
279 }
280 tokio::time::sleep(REOPEN_AFTER).await;
281 }
282 })
283}
284
285fn checking(weak: Weak<Supervisor>, detector: Arc<dyn DetectorProbe>) -> JoinHandle<()> {
288 tokio::spawn(async move {
289 let mut first = true;
290 loop {
291 let Some(interval) = weak
292 .upgrade()
293 .map(|held| held.config().observation_interval)
294 else {
295 return;
296 };
297 if !first {
298 tokio::time::sleep(interval).await;
299 }
300 first = false;
301 let Some(supervisor) = weak.upgrade() else {
302 return;
303 };
304 let checking = Arc::clone(&supervisor);
305 let probe = Arc::clone(&detector);
306 let checked = tokio::task::spawn_blocking(move || {
307 block_on(checking.check_detector(probe.as_ref()))
308 })
309 .await;
310 if let Ok(Ok(Some(turn))) = checked {
311 run_turns(&supervisor, vec![turn]);
312 }
313 }
314 })
315}