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