1use std::collections::{HashMap, VecDeque};
11use std::time::{Duration, Instant};
12
13use crate::acq::AcqStatus;
14use crate::capture::Capture;
15use crate::device::{is_timeout, Device};
16use crate::error::{Error, Result};
17use crate::proto::{self, PointPacket, Status};
18use crate::reg::{self, RegIo};
19
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22pub struct StreamStats {
23 pub packets: u64,
25 pub bytes: u64,
27 pub duplicates: u64,
29 pub nacks_sent: u64,
31 pub seqs_requested: u64,
33 pub acks_sent: u64,
35 pub heartbeats: u64,
37 pub retransmitted: u64,
39}
40
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub struct RunSummary {
44 pub device: AcqStatus,
46 pub stream: StreamStats,
48}
49
50const FEEDBACK: Duration = Duration::from_micros(250);
51const KEEPALIVE: Duration = Duration::from_millis(5);
52const HOLDOFF: Duration = Duration::from_micros(500);
53const PER_PACKET: Duration = Duration::from_micros(30);
54const MAX_SCAN: u32 = 8192;
55
56fn before(a: u32, b: u32) -> bool {
57 (a.wrapping_sub(b) as i32) < 0
58}
59
60pub struct Stream<'d> {
82 dev: &'d mut Device,
83 base: u32,
84 upper: u32,
85 pending: HashMap<u32, Vec<u8>>,
86 requested: HashMap<u32, Instant>,
87 sent_hist: VecDeque<(Instant, u32)>,
88 tail: u32,
89 last_ack: u32,
90 last_ack_time: Instant,
91 last_feedback: Instant,
92 ended: [bool; 2],
93 stats: StreamStats,
94 rx: Vec<u8>,
95}
96
97impl<'d> Stream<'d> {
98 pub(crate) fn start(dev: &'d mut Device) -> Result<Stream<'d>> {
99 crate::acq::ensure_idle(dev)?;
101 if dev.read_reg(reg::GATE_CTRL)? & reg::GATE_REJECTED != 0 {
104 dev.write_reg(reg::GATE_CTRL, reg::GATE_REJECTED)?;
105 }
106 let s = Stream::attach(dev)?;
107 s.dev.write_reg(reg::GATE_CTRL, 1)?;
108 if s.dev.read_reg(reg::GATE_CTRL)? & reg::GATE_REJECTED != 0 {
109 return Err(Error::Busy("START rejected: another acquisition was started in the meantime".into()));
110 }
111 Ok(s)
112 }
113
114 pub fn recv_into(&mut self, cap: &mut Capture, timeout: Duration) -> Result<bool> {
116 let deadline = Instant::now() + timeout;
117 while !self.is_finished() {
118 let left = deadline.saturating_duration_since(Instant::now());
119 match self.recv(left.min(Duration::from_millis(100)))? {
120 Some(p) => cap.push(&p)?,
121 None if left.is_zero() => return Ok(false),
122 None => {}
123 }
124 }
125 Ok(true)
126 }
127
128 pub fn collect(mut self, idle_timeout: Duration) -> Result<Capture> {
131 let mut cap = Capture::new();
132 let mut idle = Instant::now();
133 while !self.is_finished() {
134 match self.recv(Duration::from_millis(100))? {
135 Some(p) => {
136 cap.push(&p)?;
137 idle = Instant::now();
138 }
139 None if idle.elapsed() > idle_timeout => {
140 return Err(Error::Timeout(format!("no data for {:.1} s; {} + {} points received (no CONV events?)",
141 idle_timeout.as_secs_f64(), cap.group(0).len(), cap.group(1).len())));
142 }
143 None => {}
144 }
145 }
146 cap.finish(self.finish()?)
147 }
148
149 pub fn attach(dev: &'d mut Device) -> Result<Stream<'d>> {
153 let v = dev.read_regs(reg::NEXT_SEQ, 2)?;
154 let (next, acked) = (v[0], v[1]);
155 if next != acked {
156 dev.data.send_to(&proto::encode_ack(next), dev.dev_data)?;
157 }
158 let mut rx = vec![0u8; 9216];
160 let t_end = Instant::now() + Duration::from_millis(30);
161 while Instant::now() < t_end {
162 match dev.data.recv_from(&mut rx) {
163 Ok(_) => {}
164 Err(e) if is_timeout(&e) || e.kind() == std::io::ErrorKind::ConnectionReset => {}
165 Err(e) => return Err(e.into()),
166 }
167 }
168 let now = Instant::now();
169 Ok(Stream {
170 dev,
171 base: next,
172 upper: next,
173 pending: HashMap::new(),
174 requested: HashMap::new(),
175 sent_hist: VecDeque::new(),
176 tail: next,
177 last_ack: next,
178 last_ack_time: now,
179 last_feedback: now,
180 ended: [false; 2],
181 stats: StreamStats::default(),
182 rx,
183 })
184 }
185
186 pub fn recv(&mut self, timeout: Duration) -> Result<Option<PointPacket>> {
190 let deadline = Instant::now() + timeout;
191 loop {
192 if let Some(b) = self.pending.remove(&self.base) {
193 self.requested.remove(&self.base);
194 self.base = self.base.wrapping_add(1);
195 let p = PointPacket::decode(&b)?;
196 self.stats.packets += 1;
197 self.stats.bytes += b.len() as u64;
198 self.stats.retransmitted += p.retransmitted as u64;
199 if p.last {
200 self.ended[p.group as usize & 1] = true;
201 }
202 if self.base.wrapping_sub(self.last_ack) >= 64 {
204 self.feedback(Instant::now())?;
205 }
206 return Ok(Some(p));
207 }
208 let now = Instant::now();
209 if now.duration_since(self.last_feedback) >= FEEDBACK {
210 self.feedback(now)?;
211 }
212 match self.dev.data.recv_from(&mut self.rx) {
214 Ok((n, from)) => {
215 if from.ip() == self.dev.dev_data.ip() {
216 self.datagram(n);
217 }
218 }
219 Err(e) if is_timeout(&e) || e.kind() == std::io::ErrorKind::ConnectionReset => {
220 if now >= deadline {
221 return Ok(None);
222 }
223 }
224 Err(e) => return Err(e.into()),
225 }
226 if now >= deadline && !self.pending.contains_key(&self.base) {
227 return Ok(None);
228 }
229 }
230 }
231
232 fn datagram(&mut self, n: usize) {
233 let b = &self.rx[..n];
234 match proto::header(b) {
235 Some((proto::T_STATUS, _)) => {
236 if let Some(st) = Status::decode(b) {
237 self.stats.heartbeats += 1;
238 self.sent_hist.push_back((Instant::now(), st.sent_seq));
239 }
240 }
241 Some((proto::T_POINTS, _)) => {
242 let seq = u32::from_le_bytes(b[8..12].try_into().unwrap());
243 if before(seq, self.base) || self.pending.contains_key(&seq) {
244 self.stats.duplicates += 1;
245 } else {
246 self.pending.insert(seq, b.to_vec());
247 if before(self.upper, seq.wrapping_add(1)) {
248 self.upper = seq.wrapping_add(1);
249 }
250 }
251 }
252 _ => {}
253 }
254 }
255
256 fn feedback(&mut self, now: Instant) -> Result<()> {
257 self.last_feedback = now;
258 if self.base != self.last_ack || now.duration_since(self.last_ack_time) >= KEEPALIVE {
259 self.dev.data.send_to(&proto::encode_ack(self.base), self.dev.dev_data)?;
260 self.last_ack = self.base;
261 self.last_ack_time = now;
262 self.stats.acks_sent += 1;
263 }
264 while let Some(&(t, s)) = self.sent_hist.front() {
266 if now.duration_since(t) < HOLDOFF {
267 break;
268 }
269 if before(self.tail, s) {
270 self.tail = s;
271 }
272 self.sent_hist.pop_front();
273 }
274 let upper = if before(self.upper, self.tail) { self.tail } else { self.upper };
275 let span = upper.wrapping_sub(self.base);
276 if span == 0 || span > 0x7FFF_FFFF {
277 return Ok(());
278 }
279 let mut ranges: Vec<(u32, u16)> = Vec::new();
280 let mut queued = 0u32;
281 for i in 0..span.min(MAX_SCAN) {
282 let seq = self.base.wrapping_add(i);
283 if self.pending.contains_key(&seq) {
284 continue;
285 }
286 if self.requested.get(&seq).is_some_and(|due| now < *due) {
287 continue;
288 }
289 match ranges.last_mut() {
290 Some((first, count)) if first.wrapping_add(*count as u32) == seq && *count < 1024 => *count += 1,
291 _ => {
292 if ranges.len() == proto::MAX_NACK_ENTRIES {
293 break;
294 }
295 ranges.push((seq, 1));
296 }
297 }
298 self.requested.insert(seq, now + HOLDOFF + PER_PACKET * queued);
299 queued += 1;
300 }
301 if !ranges.is_empty() {
302 self.dev.data.send_to(&proto::encode_nack(&ranges), self.dev.dev_data)?;
303 self.stats.nacks_sent += 1;
304 self.stats.seqs_requested += queued as u64;
305 }
306 Ok(())
307 }
308
309 pub fn is_finished(&self) -> bool {
311 self.ended[0] && self.ended[1]
312 }
313
314 pub fn group_finished(&self, g: usize) -> bool {
316 self.ended[g & 1]
317 }
318
319 pub fn stop(&mut self) -> Result<()> {
321 self.dev.stop()
322 }
323
324 pub fn device(&mut self) -> &mut Device {
326 self.dev
327 }
328
329 pub fn stats(&self) -> StreamStats {
331 self.stats
332 }
333
334 pub fn finish(mut self) -> Result<RunSummary> {
336 self.dev.data.send_to(&proto::encode_ack(self.base), self.dev.dev_data)?;
337 self.stats.acks_sent += 1;
338 std::thread::sleep(Duration::from_millis(20));
339 let device = AcqStatus::read(self.dev)?;
340 Ok(RunSummary { device, stream: self.stats })
341 }
342}
343
344impl Drop for Stream<'_> {
345 fn drop(&mut self) {
346 let _ = self.dev.data.send_to(&proto::encode_ack(self.base), self.dev.dev_data);
348 }
349}
350
351#[allow(dead_code)]
352fn _assert_error_is_send_sync() {
353 fn f<T: Send + Sync>() {}
354 f::<Error>();
355}