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