1use std::io::Write;
4
5use crate::channel::{Channel, ChannelMask};
6use crate::error::{Error, Result};
7use crate::proto::PointPacket;
8use crate::stream::RunSummary;
9
10#[derive(Clone, Debug, Default)]
12pub struct GroupData {
13 channels: ChannelMask,
14 columns: Vec<Vec<i16>>,
15 pub times: Vec<u64>,
17 pub sources: Vec<u8>,
19 pub bad_points: Vec<u32>,
21 pub t0: Option<u64>,
23 points: usize,
24}
25
26impl GroupData {
27 pub fn len(&self) -> usize {
29 self.points
30 }
31
32 pub fn is_empty(&self) -> bool {
34 self.points == 0
35 }
36
37 pub fn channels(&self) -> ChannelMask {
39 self.channels
40 }
41
42 pub fn channel(&self, ch: Channel) -> Option<&[i16]> {
44 let col = self.channels.iter().position(|c| c == ch)?;
45 Some(&self.columns[col])
46 }
47
48 pub fn mean_interval_samples(&self) -> Option<f64> {
50 let (first, last) = (self.times.first()?, self.times.last()?);
51 (self.times.len() > 1).then(|| (last - first) as f64 / 64.0 / (self.times.len() - 1) as f64)
52 }
53}
54
55#[derive(Clone, Debug, Default)]
58pub struct Capture {
59 groups: [GroupData; 2],
60 pub summary: RunSummary,
62}
63
64impl Capture {
65 pub fn new() -> Capture {
67 Capture::default()
68 }
69
70 pub fn group(&self, g: usize) -> &GroupData {
72 &self.groups[g & 1]
73 }
74
75 pub fn push(&mut self, p: &PointPacket) -> Result<()> {
77 let g = &mut self.groups[p.group as usize & 1];
78 if g.points == 0 && g.columns.is_empty() {
79 g.channels = p.channels;
80 g.columns = vec![Vec::new(); p.channels.len()];
81 }
82 if p.channels != g.channels {
83 return Err(Error::Protocol(format!("group {}: channel mask changed within a run", p.group)));
84 }
85 if p.first_index as usize != g.points {
86 return Err(Error::Protocol(format!("group {}: packet starts at point {}, expected {}", p.group, p.first_index, g.points)));
87 }
88 if p.is_empty() {
89 return Ok(());
90 }
91 if g.t0.is_none() {
92 g.t0 = Some(p.t0);
93 }
94 for (col, v) in g.columns.iter_mut().enumerate() {
95 v.extend(p.column(col));
96 }
97 if p.has_time {
98 for pt in p.points() {
99 g.times.push(pt.time.unwrap_or(0));
100 g.sources.push(pt.source.unwrap_or(0));
101 if pt.bad {
102 g.bad_points.push(pt.index);
103 }
104 }
105 }
106 g.points += p.len();
107 Ok(())
108 }
109
110 pub fn finish(mut self, summary: RunSummary) -> Result<Capture> {
112 let d = &summary.device;
113 self.summary = summary;
114 if d.lost != 0 || d.dropped != 0 {
115 return Err(Error::Device(format!("{} events lost in the engine (CONV rate too high for the kernel), {} records dropped before the network",
116 d.lost, d.dropped)));
117 }
118 for g in 0..2 {
119 if self.groups[g].points != d.group_points[g] as usize {
120 return Err(Error::Protocol(format!("group {g}: {} points received, device reports {}", self.groups[g].points, d.group_points[g])));
121 }
122 }
123 Ok(self)
124 }
125
126 pub fn write_csv<W: Write>(&self, mut w: W) -> Result<()> {
128 let all = ChannelMask::from_bits(self.groups[0].channels.bits() | self.groups[1].channels.bits());
129 write!(w, "group,index,time,source")?;
130 for c in all.iter() {
131 write!(w, ",{c}")?;
132 }
133 writeln!(w)?;
134 for (gi, g) in self.groups.iter().enumerate() {
135 for i in 0..g.points {
136 write!(w, "{gi},{i},")?;
137 match (g.times.get(i), g.sources.get(i)) {
138 (Some(t), Some(s)) => write!(w, "{t},{s}")?,
139 _ => write!(w, ",")?,
140 }
141 for c in all.iter() {
142 match g.channel(c) {
143 Some(v) => write!(w, ",{}", v[i])?,
144 None => write!(w, ",")?,
145 }
146 }
147 writeln!(w)?;
148 }
149 }
150 Ok(())
151 }
152}